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

andyandy's avatar

->with() is sometimes Session, sometimes variable, why?

EXAMPLE 1:

return redirect('/')->with('success', 'Passport added!');

This is later addressed as: session('success')

EXAMPLE 2:

$data=['first' => $first, 'second' => $second]; return view('id')->with($data);

This is later addressed as variables $first, $second (i can give similar example when it is array)

How comes ->with() once is just a variable/array. And another time it's a session?

0 likes
6 replies
Nakov's avatar

Because the response type is different. When you redirect, then you are hitting another controller action which returns the view that needs to be displayed. So in order to preserve the data that you are trying to pass, laravel uses flash session using the with() method: https://laravel.com/docs/7.x/redirects#redirecting-with-flashed-session-data

And when you respond with an HTML rendered view, using the view() helper, the with() method passes the data directly to the view and you get the values that you've passed by using their keys (variables): https://laravel.com/docs/7.x/views#passing-data-to-views

1 like
andyandy's avatar

When I'm using ""->with()"" with redirect and when I'm using ""->with()"" with views, each time ""->with()"" is a different method with just same name? Or is it same method with just different/adjusted behavior?

Nakov's avatar

The name of the method is the same, it is called on two different objects, and the behavior is different.

It is like two guys with the same name 😃 nothing wrong with that.

andyandy's avatar

This explains it completely, now I understand!

Thank you guys.

Please or to participate in this conversation.