mauricius / laravel-htmx

Laravel helper library for Htmx
MIT License
308 stars 14 forks source link

Session Support #15

Closed saeedvaziry closed 10 months ago

saeedvaziry commented 10 months ago

Hello, Thanks for the great package! Does it also handles the flash sessions? For example I want to handle the following:

session()->flash('status', 'success');
return back();
davidjr82 commented 10 months ago

The session is not managed by this package. You just need to know how the lifecycle of the request is and put it in the context of your application.

For example, if you are going to make a redirect, as in your example, then it works as in any other Laravel app. But if you are going to return a html fragment that will be injected in the actual dom, without redirecting, then flashing the session would not work because there is no redirect and the session flash will not be rotated. In that case, for example, something like this would work:

session()->now('status', 'success');
return view('my-view');

I hope it helps.

saeedvaziry commented 10 months ago

Thanks @davidjr82 for the reply. When using the redirect of the package with a flash session it actually does the flash session and it reaches to the next render but htmx grabs the HX-Location and does the actual redirect which makes the flash session disappear. So technically 2 redirects happening from my understanding.

davidjr82 commented 10 months ago

The way Laravel works is the following:

Browser -> Request to controller -> Controller handles it, flash data into the session and returns a response with a 302 redirect -> the browser reloads to that URL -> the new request is handled by the middleware and the flashed data in the session is rotated and available to this new request -> returns the new view to the user.

When you use the HX-Location this schema is similar, the only difference is that the response is a 200 with an HX-Location header that will perform the redirect through javascript instead of being the browser who directly performs it.

So under this scenario, flashing data into the session will work as expected with any regular Laravel app.

The only scenario where it changes is when you want to replace a part of the DOM with hx-target, because in this case the browser will not make an additional request. In that case, to have the session data available when you render the view, is where you need to do session()->now(...) before returning the view, so the session data is available in that same request.