Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lifesound's avatar

Laravel session and undefined value

       	 $invoice = Invoice::with('items')->where('number' ,$request->invoice)->where('tel' ,$request->telNumber)->first();
        	if($invoice) {
          	  // return $invoice;
       	     $request->session()->put('invoice', $invoice);
     	       return redirect('/step2');
    	    }

is it the right way to save resulted data ( invoice to the session ?

I am trying to get that data

  	      if ($request->session()->has('invoice')) {
      	      $invoice = session()->get('invoice');
   	     };

is there anything wrong here ? because i have undefined $invoice ?

0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

If you are using the $invoice outside of your if check you'll get undefined.

I will avoid storing the FULL eloquent instance of the $invoice and store just the id instead and than just get it from the model.

I would also do a redirect->with so it uses a flash session, because the way you store it now it will stay there until you override it or the session expires, which can lead to trouble.

so just use:

return redirect('/step2')->with('invoice_id', $invoice->id);

in your step2 action:

Invoice::find(session('invoice_id'));
1 like
Sinnbeck's avatar

I agree with nakov.

One thing. You are loading items here, but never use them. Only load what you need, when you need it

1 like
Sinnbeck's avatar

@lifesound if you only need the id you can even make it cleaner. Just a little extra tip

$invoiceId = Invoice::where('number' ,$request->invoice)->where('tel' ,$request->telNumber)->value('id');
        	if($invoiceId) {
                 return redirect('/step2')->with('invoice_id', $invoiceId);
           } 

Please or to participate in this conversation.