I’m doing a dashboard frontend for a Laravel back-end, and there are a lot of ajax requests from many sources, my end goal is to have a file like api.js
that encapsulates all my api logic, I wanted to be able to reuse Laravel validation rules to validate all my api requests.
example form request:
<?php
namespace AppHttpRequestsDoctorProfile;
use AppHttpRequestsApiRequest;
class GetAppointments extends ApiRequest
{
...
public function rules()
{
return [
'doctor_id' => 'required|integer|min:0',
'date' => 'date_format:Y-m-d',
];
}
...
}
I searched and found these two libraries:
these two are good but the problem is they both focus on Form elements but there are many requests that still need validation but the values don’t exist in a single form!
I thought about it and a possible hack is to have a hidden Form and i can add values to it via js then use Laravel Javascript Validation to send the request.
I don’t have that much front-end experience so i wanted to ask here and make sure im not doing anything terribly wrong bfore resorting to such hacks:D
2
Answers
You can use Laravel Precognition, this will allow you to use your backend validation rules in the frontend, without having to rewrite any of the rules in the frontend.
While reusing Laravel’s validation rules on the frontend exactly as is isn’t typically feasible due to differences in languages (PHP vs JavaScript), you can mimic their behavior using various front-end validation libraries.
For AJAX requests, you can handle validation on the server-side within your Laravel application and then return the validation errors as JSON responses. On the front-end, you can then handle these responses and display the appropriate error messages. This keeps your validation logic centralized within Laravel.
For example, in your Laravel back-end:
And then, on your front-end AJAX call, handle these validation error responses accordingly:
This way, you can handle all sorts of AJAX requests, not just form submissions, and you can also take advantage of Laravel’s comprehensive validation system.