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(); }}