DEV Community

loading...
Cover image for Form Requests Validation In Laravel 8

Form Requests Validation In Laravel 8

Funke Olasupo
Backend Engineer | Volunteer | Technical Author | Public Speaker | God-loverπŸ’ž
Originally published at roxie.hashnode.dev ・6 min read

As a back-end engineer, dealing with forms is almost inevitable. I'll be doing a short guide on how to use Form Requests to validate data requests in Laravel
8.

The prominent way of validating data requests in Laravel is by using the validate method or validator facade in our controller like this:

Validate method

Validate

Validator Facade

Validator

Now there is absolutely nothing wrong with this method but think about scenarios where you need to perform a validation logic more than once, this is one advantage of Form Requests.

Form Requests

So, what are Form Requests?
Form requests are custom request classes that encapsulate their own validation and authorization logic.
Due to this, you really don't need to clutter your controller with any validation logic. They allow you abstract validation logic from the controller to a single class. They also aid the reusability of any validation logic in the controller.

One more benefit😍 is that you can also customize your validation error messages. Amazing right?πŸ˜‰
I consider Form Requests an awesome Laravel feature and it will be great if many engineers can adopt it.

I'll be creating a basic User Registration API with Form Requests Validation, so follow through carefully.πŸ‘Œ

Step 1: Set up Controller

To create a controller class, you may use the make:request Artisan CLI command:

php artisan make:controller UserController
Enter fullscreen mode Exit fullscreen mode

This controller class will be created at app\Http\Controllers\UserController.php. Then we define a method register() in that controller that will perform all the instructions for registering a new user.

   public function register(){
      //code...  
    }
Enter fullscreen mode Exit fullscreen mode

All the necessary actions to be carried out on the incoming data when a user registers will be in this register method but before that, we will need to validate the incoming data.

Step 2: Setting up our Model and Database Migrations simultaneously.

PS: If you use PhpMyAdmin, create the database only with the database name, then in your .env file assign the name of the database DB_DATABASE before running migrations. If it is the same as the project name, then you don't need to change it, it will be set to default already.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=qouteapp
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

To create a model and migration, you may use this make:request Artisan CLI command:

php artisan make:model User -m
Enter fullscreen mode Exit fullscreen mode

A User model and migration come default with a laravel project so the above won't work for me, but have that in mind for creating your model and migration.

Now, I need the users' email, username, and password to register. Go to the migration file and set up the schema/structure of your table, which will be in create_users_table.php in the migrations folder.

 Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();
            $table->string('username');
            $table->string('password');
            $table->timestamps();
        });
Enter fullscreen mode Exit fullscreen mode

To run your migration, you may use the migrate Artisan CLI command:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Now your database is completely set.πŸŽ‰

Step 3: Setting up our endpoints in api.php in the routes folder.

We need to define our endpoints through which a user can make a request to register.

First, we import the UserController.

use App\Http\Controllers\UserController;

Enter fullscreen mode Exit fullscreen mode

Then,

Route::post('/user/register', [
    UserController::class, 'register'
]);
Enter fullscreen mode Exit fullscreen mode

Step 4: Setting up Form Request.

We need to validate incoming data requests before executing controller instructions to that data.

To create a form request class, you may use the make:request Artisan CLI command:

php artisan make:request UserRegisterRequest
Enter fullscreen mode Exit fullscreen mode

The form request class created will be in the app/Http/Requests/UserRegisterRequest.php but if this directory doesn't exist this command creates one for you.

The form request class comes with 2 methods; authorize() and rules() by default.

  • authorize()

This method determines if an authenticated user has the authority to make a request to a given resource. It returns a boolean. If it returns true then all authenticated users can make such a request but if it returns false it means no user either authenticated or not can make such a request. It returns false by default.

Asides from this, you can also give or restrict access rights to specific users regarding a resource.
(PS: Further detailed explanation about this will be the advanced course of this guide).

public function authorize()
    {
        return true;
    }
Enter fullscreen mode Exit fullscreen mode
  • rules()

This method returns an array of validation rules for the incoming data request. It is the same rules and syntax as if you were validating in your controller based on what you're validating for.

public function rules()
    {

            return [
                'email'=>'required|email|bail|unique:users',
                'username' => 'required|bail',
                'password'=>'required|bail'
            ];

    }
Enter fullscreen mode Exit fullscreen mode

Now that we have set our authorize() and rules() methods, we can do one more thing to make this customized.😍 Remember I said earlier that we can customize our error messages if any of our validation fails.

You can customize the error messages used by the form request by overriding the default Laravel messages() method. This method should return an array of attribute/rule pairs and their corresponding error messages:

public function messages()
    {
        return [
            'email.required'=>'Email Is Required',
            'email.email'=>'Enter a valid Email',
            'email.bail'=>'Email Is Required',
            'email.unique'=>'Email has been Taken',
            'username.required'=>'Username Is Required',
            'username.bail'=>'Username Is Required',
            'password.required'=>'Password Is Required',
            'password.bail'=>'Password Is Required'

        ];
    }
Enter fullscreen mode Exit fullscreen mode

Now we can move back to the controller to give instructions to be carried out on the validated data.

Step 5: Finish Setting up the Controller

Now back to the UserController, we want to save the validated data into our database.

First, we import the User model and the UserRegisterRequest outside the class in the UserController.php.
The UserRegisterRequest and a variable $request are passed as a parameter in the register method.
A new user is created and the validated data for that user is passed into that user instance and then saved.

namespace App\Http\Controllers;
use App\Models\User;
use App\Http\Requests\UserRegisterRequest;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function register(UserRegisterRequest $request){

        $user = new User();
        $user->email=$request->input('email');
        $user->username=$request->input('username');
        $user->password= bcrypt($request->input('password'));

        $user->save();
        return response()->json([
            'message'=>'Registration Successful'
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

In summary, if a user registers successfully and all his input information is stored then a JSON response is returned.

Finally, let's test to see if this really works.😏

Step 6: Testing API with Postman.

PS: We will have to set our header to accept JSON and if you'll be cloning my Github repository, I already created a middleware for that.

Screenshot (68).png

So I accurately filled in the required fields in their valid format respectively and it returned the output of a JSON response saying 'Registration Successful'. Amazing right?πŸ€—πŸ˜

Successful

To verify if our Form Request Validation works I didn't fill in anything for email and it returned the output of my error message where email is required saying ''Email is required".

Validate works

Congratulations on your new knowledge acquisition!πŸŽ†πŸ₯°

WoahπŸ€©πŸ€—! This has been a thrilling and exciting journey for me, I hope it was for you too.😘

Guess what?πŸ˜‹The entire code for this is open source here on my Github.

To make this article very comprehensive and forward, I didn't give a detailed explanation to anything asides Form Requests. Other articles will be published to properly explain other concepts like models, routes, migrations, controllers, etc.

πŸŽ‰Teaser!!πŸ˜›
There will be an advanced series of this guide coming soon and it's going to contain:

  • Adding After Hooks To Form Requests

  • Authorizing Form Requests(Restricting and authorizing certain users access rights)

  • Customizing The Validation Attributes

Stay tuned😘

If you have a buttressing or conflicting view of anything here, please reach out to me on Twitter.

Thanks for reading.🀝

Discussion (0)