0

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
                );
1
  • Hi, it's not clear your intention, Keyboard class is receive a single array argument?, are you using varidic params to receive an N number arguments? or are you receiving an string comma separated? Commented Jun 17, 2020 at 16:49

2 Answers 2

4

You can use ... operator to pass parameters. But check before whether size of an array is proper.

$keyboard = new Keyboard(...$titles);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.