0

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

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

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.