Samyoul Samyoul - 4 months ago 77x
PHP Question

An Elegant Way to Persist Laravel Input Data to the Session

I'm trying to find if there is an elegant way to pass data from the request->input() into the request->session(); . What I'm trying to achieve is to receive user input which I'd like to then reuse in subsequent http requests.

The Ugly Way:

I can do this in an ugly way:

$request->session()->put('name', $request->input('name'));
$request->session()->put('address', $request->input('address'));
$request->session()->put('age', $request->input('age'));
$request->session()->put('bed_time', $request->input('bed_time'));

The Laravelly Way:

But that doesn't seem very Laravelly, I feel like there should be a way so that I could do something like:




Unfortunately I can't find anything in the docs that gives me a nicer way to implement this. Is there a way to achieve this? Or am I stuck with this ugly unlaravelly way of persisting data into the session?

Edit :

I've accepted Jeff's answer as the solution to my problem. Which partially details the Laravelly way of approaching this problem.


Above is the solution on the request that received the input data. However in all subsequent http requests I need to include the following, and access the data like such.

//This makes the data available for the next request.

// I can access the data from the last request using the 'old' method.
$name = $request->old('name');
$address = $request->old('address');

I need to reflash everytime I want to pass the data down the line another request.


See this manual page. It covers flashing data to session for the next request, which may be what you're after:


This will take all of your old input fields and store them in the session's flash data, keeping them there until the next request. This is useful if, for instance, a user inputs data that does not validate and you wish to redirect with the old data so that you can prepopulate form fields. In fact, there's an easier way to return both a redirect and flash the same data into session:

return redirect()->back()->withInput();

You can even specify data that you do not want to keep:

return redirect()->back()->withInput($request->except('password'));