While HTMX is not a new library, it’s becoming more and more popular for its practicality and simplicity.
For Laravel developers who are not too crazy about new frontend frameworks that are coming out sporadically, this might be a perfect solution.
If you are reading this post and are new to the HTMX (which I doubt), you can check out Andre Madarang’s introduction video.
Rendering
When it comes to rendering, usually I go for the most simple way, which is rendering the view as partial.
public function edit($id)
{
return view('user.edit', ['data' => '...']);
}
Second option would be to use Laravel’s built-in Blade fragments feature.
Redirecting
In some cases, instead of working with AJAX, you may want to redirect/refresh the page. HTMX is checking the response for several headers, and one of them is HX-Redirect.
We can utilize this header to redirect at the end of a POST request, for example.
public function editPost($id)
{
return response('', 302)->header('HX-Redirect', $url);
}
Furthermore, we can make a macro for this type of response by adding it to the AppServiceProvider inside the boot method.
public function boot(): void
{
Response::macro('htmxRedirect', function($url, $status = 200) {
return response('', $status)->header('HX-Redirect', $url);
});
}
And use it like this:
public function editPost($id)
{
return response()->htmxRedirect('...');
}
Validation
When it comes to Laravel’s validation and HTMX, it’s a little bit tricky but still manageable.
There are a few ways to go about this. One of them would be to validate with the Validator instance and return errors to the partial, where you can process/print the MessageBag.
public function editPost(Request $request)
{
$validator = \Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return view('user.partials.edit-form', [
'errors' => $validator->erros(),
]);
}
// ...
}
But I like using Blade’s @error directive, which reads errors that are flashed to the session by validator.
In order to mimic that, we have to flash the errors manually before rendering the partial view.
public function editPost(Request $request)
{
$validator = \Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
request()->flash();
session()->ageFlashData();
View::share('errors', (new ViewErrorBag)->put('default', $validator->errors()));
return view('user.partials.edit-form', $data);
}
// ...
}
Extra: You can make a helper function, or adding a function to trait or directly to the Controller.php and use a 1-liner.
public function editPost(Request $request)
{
$validator = \Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
$this->flashErrors($validator->errors());
return view('user.partials.edit-form', $data);
}
// ...
}
Hopefully you found this article helpful, and I hope you will enjoy your HTMX journey!