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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners