Source: juststeveking.uk

Valid validators validating data
Validation is a must-have for any modern project, and in Laravel, it is super simple to get started. Within your controller methods, you can call a method, pass in the request, and an array of the rules you wish to validate with.

My form request would look something like this: namespace App\Http\Requests\Api\Posts; class StoreRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ 'title' => ['required', 'string', 'min:2', 'max:255',] 'content' => ['required', 'string'], 'category_id' => ['required', 'exists:categories,id'], ]; }}

namespace App\Validators\Posts; class StoreValidator implements ValidatorContract { public function rules(): array { return [ 'title' => ['required', 'string', 'min:2', 'max:255',] 'content' => ['required', 'string'], 'category_id' => ['required', 'exists:categories,id'], ]; } public function messages(): array { return [ 'category_id.exists' => 'This category does not exist, you Doughnut', ]; }}

Our controller will look the same as we have already moved validation out, so let’s instead look at the form request: namespace App\Http\Requests\Api\Posts; class StoreRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return (new StoreValidator())->rules(); }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners