Reputation: 6622
suppose we have an Object that accept some value as array that is separated by comma:
$keyboard = new Keyboard(
['value1'],
['value2'],
['value3'],
['value4']
);
Now I want to fetch some value from database via a loop and send them finally to that object. but I do not know how can I collect them and send a comma separated list of them.
I write this code But can not get appropriate result from it:
$brands = Option::with('translations')->whereHas('attribute', function ($query) {
$query->where('type', '=', 'brand');
})->get();
$titles = [];
foreach ($brands as $key => $brand) {
$titles [] = array($brand->title_fa);
}
$keyboard = new Keyboard(
$titles
);
Upvotes: 0
Views: 203
Reputation: 10652
You can use ...
operator to pass parameters. But check before whether size of an array is proper.
$keyboard = new Keyboard(...$titles);
Upvotes: 4
Reputation: 1252
First I suggest plucking the value that you want and then map them
Look at the Laravel Collection methods to avoid doing unnecessary loops and doing it more fluent
https://laravel.com/docs/7.x/collections
$brands = Option::with('translations')->whereHas('attribute', function ($query) {
$query->where('type', '=', 'brand');
})->get()
->pluck('title_fa')
->map(function($brand){ return [$brand]; })->all()
Now you have a $brands
array as required
So you can pass it as an array or as a Varidic params using the Splat operator as suggested in the other answer
$keyboard = new Keyboard($brands);
$keyboard = new Keyboard(...$brands);
Upvotes: 1