Back to articles
Alpine.js Plugin for Laravel AJAX Validation Errors

Alpine.js Plugin for Laravel AJAX Validation Errors

via Dev.to JavaScriptRecca Tsai

Originally published at recca0120.github.io When Laravel validation fails on a regular form submission, you can use the @error directive in Blade to display errors. But for AJAX requests, Laravel returns errors in JSON format, and you need to handle the frontend display yourself. Blade's @error Only Works for Synchronous Forms The typical approach: <label for="email">Email</label> <input id="title" type="email" name="email" class="@error('email') is-invalid @enderror"> @error('email') <div class="alert alert-danger">{{ $message }}</div> @enderror But when the request is AJAX, Laravel returns JSON: { "errors" : { "email" : [ "The email field must be a valid email address." ], "name" : [ "The name field is required." ] }, "message" : "The name field is required. (and 1 more error)" } To avoid having to learn a separate frontend error handling approach, I wrote an Alpine.js plugin that provides an API similar to Laravel's MessageBag . Alpine.js errors plugin // errors.js class MessageBag

Continue reading on Dev.to JavaScript

Opens in a new tab

Read Full Article
3 views

Related Articles