Home > Software engineering >  adding new array into an existing laravel collection
adding new array into an existing laravel collection

Time:11-01

I have created a session that stores an array, now I am facing a problem if I want to add more items into the session array

 if(session()->has('key')){

            $tests = Test::all()->where('id', 3);
           $res = collect($tests);
            session()->push('key',  $res);

         }else{
            $tests = Test::where('id', 1)->get();
            $res = collect($tests);
            session()->put('key',  $res);


        }

if I die and dump the session result this is what I get

enter image description here

this is the result that I want

enter image description here

CodePudding user response:

Where you're going wrong is that you're getting a Collection of Tests and adding that to the array, not an individual Test (I'm working on the basis that you're only wanting to add one Test to the session at a time).

Take your first line :

$tests = Test::all()->where('id', 3);

This will only return one Test, as presumably "id" is unique, but it will return a Collection with the one Test, not just the Test itself.

You could do this to just return a Test, not a Collection :

$test = Test::where('id', 3)->first();

But (again, presuming) "id" is unique, it's easiest to just use "find", like so :

$test = Test::find(3);
session()->push('key',  $test);

This will return just the Test.

If you do want to add multiple Tests to the session in one go, then first get the collection :

$tests = Test:where('id', '>', 10)->get();

Then loop through them and add each test to the array individually :

foreach($tests as $test) { 
    session()->push('key',  $test);
}
  • Related