Jefsama Jefsama - 4 months ago 6
PHP Question

Laravel Reproduce an array given by the eloquent model

I am new in laravel. Right now i am struggling on how to redeclare the array given by the eloquent model.

PHP code

$data = Commission::select(['uploads_id'])->where([
'affiliate_code' => $id
])->get()->toArray();
var_dump($data);


var_dump Output

array(3) {
[0]=>
array(1) {
["uploads_id"]=>
string(2) "24"
}
[1]=>
array(1) {
["uploads_id"]=>
string(2) "26"
}
[2]=>
array(1) {
["uploads_id"]=>
string(2) "27"
}
}


i want the
$data
to be redeclare like this.

$data = [24 , 25 , 26]


is there a way on it or different approach?

Answer

When you call get() method on Laravel Builder Object, it will return a Collection Object to you. And there are so many nice helpers you can use instead of getting your hands dirty with php array. You can find references here.

In your scenario, this can be done by

Commission::select(['uploads_id'])->where([
    'affiliate_id' => $id
])->get()->pluck('uploads_id');

Pluck() is a Collection method and it's documentation can be found here. Remember to cast it to php array with ->all() or ->toArray(). It's useful to be familiar with Collection in Laravel.

Good luck!

Comments