Laravel eloquent gives an array of numbers instead of integers

I am trying to return id as a string and pass them via api (using to select later)

Using Laravel resouces:

public function toArray($request)
{

    return [
        'speciality' => $this->specialities()->pluck('speciality_id')
    ];
}

and it returns an array of numbers, for example:

[1, 3, 5, 7]

How can I convert them to an eloquent request and return as a string?

["1", "3", "5", "7"]
+4
source share
2 answers

A bit awful , but if you have no choice, cast it to a string

protected $casts=[
    'speciality_id'=>'string'
];
+1
source

You can loopthrough the array, castpass it to a string and add to new array, since this is only required for this case specific.

$a = [1, 3, 5, 7];
$b = array();
foreach($a as $as)
        $b[] = (string)$as;

return $b;

Or is it better to use array_map()-

$a = array_map(function($value){
        return (string) $value;
}, $a);
+2
source

Source: https://habr.com/ru/post/1692872/


All Articles