Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your requests.

This is achieved by making use of the artisan command make:request

php artisan make:request StoreTagRequest

Alternatively if using the same validation for Store and Update you you also just name this TagRequest.

This creates a file in app/Http/Requests called StoreInstanceRequest.php

Now you can place in your validation rules into the rules() method as an array


namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreTagRequest extends FormRequest
    public function rules(): array
        return [
            'name' => 'string|required|max:32',
            'enabled' => 'boolean|required',
            'priority' => 'integer|required|min:1|max:10'

To use this in the Tag store controller

use App\Http\Requests\StoreInstanceRequest;

public function store(StoreInstanceRequest $request)
   $validated = $request->validated();//The validated input request

  //Do Store....

This now enables cleaner controllers as the validation rules are not directly in the method.

You can also now re use this request validation where the rules are shared, this could be in the update method or the API.