Chapter 5 - Usage of Request Class

Hello, Artisans, welcome to the 5th chapter of being an Artisanary. Laravel is a popular PHP framework that offers a range of features and tools to simplify web development. One of the key features of Laravel is its ability to handle form validation. Laravel provides various ways to validate forms, and one of the most popular ways is by using the Form Request Class. So if you already complete the previous chapters/sections, then you're good to go, if not my recommendation would be please complete the previous chapters. Because we'll use the same old repository that we use from chapter 4. 

Note: Tested on Laravel 10.0

Table of Contents

  1. Create Form Request Class and Define validation rules
  2. Use Form Request Class in Controllers
  3. Customize error messages in Form Request Class

Create Form Request Class and Define validation rules

So for creating a form request class, at first we've to fire the below command in the terminal. But as we already said that we'll use our old repository. Because later that we'll use it for our real life works. So, fire the below command

php artisan make:request BlogRequest

It'll create a file under app/Http/Requests/BlogRequest.php, open the file and you can see the file looks like below:

BlogRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BlogRequest extends FormRequest
{
    public function authorize(): bool
    {
        return false;
    }
    public function rules(): array
    {
        return [
            //
        ];
    }
}

Where in rules() method we can provide our validation rules and authorize() method for permission-related task. But we'll keep it always true because later we'll implement role permission system and we'll handle permission-related task from their. So, look at the below source code

BlogRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BlogRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }
    public function rules(): array
    {
        $rules = [
            'title'         => 'required|string|max:255|unique:blogs,title,'.$this->id, //here this was refer to its id, it'll useful during edit mode
            'description'   => 'required'
        ];
        
        if($this->method() == 'POST') { //And we want to required image field only when some one creates a blogs, not during update. Because we'll use this vlidation for both create and update
            $rules['image'] = 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048';
        }
        return $rules;
    }
}

Let's see what's happening here,

First of all in authroize() method we'll return true, that means we don't want to authorize via request class. And then we'll define our rules in rules() method.

Use Form Request Class in Controllers

To use in controller at first we've to create a controller first, So, let's create a new one first by firing the below command.

php artisan make:controller BlogController -r

It'll create a file under app/Http/Controllers/BlogController.php, which'll look like below

BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BlogController extends Controller
{
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }
    public function store(Request $request)
    {
        //
    }
    public function show(string $id)
    {
        //
    }
    public function edit(string $id)
    {
        //
    }
    public function update(Request $request, string $id)
    {
        //
    }
    
    public function destroy(string $id)
    {
        //
    }
}

Now we've to just called the BlogRequest class, where we want to use the validation. As we need to use in the store() and update() method. So, let's modify the methods like below.

BlogController.php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\BlogRequest;
use Illuminate\Http\Request;

class BlogController extends Controller
{
    public function index()
    {
        //
    }
    
    public function create()
    {
        //
    }
    public function store(BlogRequest $request) //here we replace the default rREquest class with our BlogReequest class
    {
        //
    }
    public function show(string $id)
    {
        //
    }
    public function edit(string $id)
    {
        //
    }
    public function update(BlogRequest $request, string $id) //here we replace the default rREquest class with our BlogReequest class
    {
        //
    }
    
    public function destroy(string $id)
    {
        //
    }
}

And that's enough for validating any form.

Use Form Request Class in Controllers

For customizing error messages, request class provides another method called messages() where we can define messages for each rules. Look at the below source code.

BlogRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BlogRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }
    public function rules(): array
    {
        $rules = [
            'title'         => 'required|string|max:255|unique:blogs,title,'.$this->id,
            'description'   => 'required'
        ];

        if($this->method() == 'POST') {
            $rules['image'] = 'required';
        }
        return $rules;
    }

    public function messages(): array
    {
        return [
            'title.required'        => 'Title is required',
            'title.max'             => 'Title must be less than 255 characters',
        ];
    }
}

In this way, we can customize any error messages.

We'll see the usage of form request class in this chapter. And yes keep up to date with the Github repository. That's it for today. See you in my next chapter. Happy coding ๐Ÿ™‚ .