Development

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

<?php

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

2 years ago