htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Issue with htmx redirection behavior when using PUT method

Open Luddinus opened this issue 1 year ago • 6 comments

I'm currently facing an issue with htmx when using the PUT method in combination with redirection. Here's the scenario:

I have a form in my Laravel application that I'm submitting using htmx with the PUT method. After submitting the form, if there are validation errors, Laravel redirects back to the form page with the errors.

Problem:

The issue arises when Laravel redirects back with the errors. Instead of making a GET request to the form page, htmx seems to make another PUT request to the form URL. This causes a "Method Not Allowed" error because the form URL only accepts GET requests.

I've also tested the behavior with the GET method, and everything works as expected. When submitting the form with the GET method and encountering validation errors, htmx correctly makes a GET request to the form page upon redirection.

My code is as simple as this

<form hx-put="/users/{{ $user->id }}">
   <input name="name" value="...">

   (render errors if any)
</form>

Thanks.

Luddinus avatar Apr 18 '24 21:04 Luddinus

What http status code is used for the offending redirect?

mannih avatar Apr 19 '24 05:04 mannih

What http status code is used for the offending redirect?

302, Laravel defaults when there are session errors (422 if the request expects a json, but not the case)

Luddinus avatar Apr 19 '24 13:04 Luddinus

@Luddinus are you sending a HX-Redirect response header back from the server? I seem to remember needing to do that in Laravel for PUT and DELETE (possibly others) requests. Can we get a look at the relevant piece of your Laravel source?

defenestrator avatar Apr 22 '24 22:04 defenestrator

@mannih @defenestrator

Well, I solved this way:

<form hx-post="/users/{{ $user->id }}">
   @method('put')
   
   ...
</form>

Luddinus avatar Apr 23 '24 17:04 Luddinus

@mannih @defenestrator

Well, I solved this way:

<form hx-post="/users/{{ $user->id }}">
   @method('put')
   
   ...
</form>

That actually makes sense, thanks for sharing your workaround/solution.

defenestrator avatar Apr 23 '24 18:04 defenestrator

I was having the same issue in Laravel with PATCH and DELETE requests to controllers that redirect back to the form page and was able to solve it by using a 303 status code on the controller redirect like this:

return back(303);

guictx avatar May 20 '24 15:05 guictx