Laravel - Trigger endpoint validation only

62 Views Asked by At

I have many endpoints in Laravel that utilise FormRequests for validation. Is there a way to trigger those endpoints' validation only?

The use case for this is that I want to trigger multiple endpoints validation first and then trigger them fully if all is passing to avoid half-completed states.

The easiest way seems to be to just add a check to the controller, something like:

if($request->query('validation_only')){
    return response('', 200);
}

// Normal logic

However, it seems a bit messy to start adding those everywhere. Is there a global way (perhaps using a certain HTTP Method or Header etc.) to trigger the controller/form request validation but not trigger the logic inside the controller method?

Thanks in advance!

1

There are 1 best solutions below

0
MorganFreeFarm On

I believe that best way to achieve this is to use MIddleware, something like this:

php artisan make:middleware ValidationOnlyMiddleware

Middleware:

namespace App\Http\Middleware;

use Closure;

class ValidationOnlyMiddleware
{
    public function handle($request, Closure $next)
    {
        // Check if the request has the 'validation-only' header or query parameter set
        if ($request->hasHeader('X-Validation-Only') || $request->query('validation_only')) {
            
            // Get the original response (this will run the validation)
            $response = $next($request);

            // Check if the original response is successful
            if ($response->isSuccessful()) {
                return response('', 200);
            }
            
            // If not successful, return the original response (likely a validation error)
            return $response;
        }

        // If no 'validation-only' header/param, just continue with request
        return $next($request);
    }
}

Do not forget to register your new middleware in Kernel.php:

protected $routeMiddleware = [
    // ...
    'validation_only' => \App\Http\Middleware\ValidationOnlyMiddleware::class,
];

And finally use your Middleware in routes, like this:

Route::middleware(['validation_only'])->group(function () {
    // Your routes here
});

Or directly in controller:

public function __construct()
{
    $this->middleware('validation_only');
}