Form Requests Validation In Laravel 8
Tags: laravel, codenewbie, 100daysofcode
Published: 2021-07-05 16:18:10

  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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u23tk0z7frt8xpsccqv.png)

#### Validator Facade
![Validator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvm40hhdydf8nakoh879.jpg)




  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
php artisan make:controller UserController
```
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.

```php
   public function register(){
      //code...  
    }
```
  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.

```php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=qouteapp
DB_USERNAME=root
DB_PASSWORD=
```

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

```php
php artisan make:model User -m
```
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.
```php
 Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();
            $table->string('username');
            $table->string('password');
            $table->timestamps();
        });
```
 To run your migration, you may use the migrate Artisan CLI command:

```php
php artisan migrate
```
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.

```php
use App\Http\Controllers\UserController;

```

Then,

  ```php
Route::post('/user/register', [
    UserController::class, 'register'
]);
```

**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
php artisan make:request UserRegisterRequest
```
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).*

```php
public function authorize()
    {
        return true;
    }
```


- `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.

```php
public function rules()
    {
    
            return [
                'email'=>'required|email|bail|unique:users',
                'username' => 'required|bail',
                'password'=>'required|bail'
            ];
        
    }
```
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:

```php
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'

        ];
    }
```
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.


```php
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'
        ]);
    }
}
```
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 ](https://github.com/Roxie-32/form_requests) repository, I already created a middleware for that.

![Screenshot (68).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1617200353469/1b7zOqUw4.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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccie2hil5ab9ffthdpp6.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24mb0aq406wq7num5imf.png)


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](https://github.com/Roxie-32/form_requests).

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](https://twitter.com/OlasupoFunke).

Thanks for reading.🤝