Handle Request validation in Laravel

211
Laravel Validation

Validation is one of the most important things to do in any application. Validating form requests helps us to build a robust and secure application. Laravel provides different ways to validate user inputs. In this article, we will discuss them in more detail.

Validating form requests in a controller is a common practice. There is nothing wrong with this approach. Let’s discuss this in detail. Suppose we have ContactController to submit the contact details. We want to save the records inside the store method. Then our validation looks like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate data
        $this->validate($request, [
            'name'    => 'required',
            'email'   => 'required|email',
            'phone'   => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'subject' => 'required',
            'message' => 'required'
        ]);

        // data validated. proceed with data
    }
}

The above code works perfectly fine. But, it’s always a good practice to separate Validation logic and controller operation. The good news is that Laravel provides the Form Request feature to separate this logic from the controller. For this, we need to create a Form Request and write the validation logic.

To create a new form request, we need to run the following code.

php artisan make:request ContactFormRequest

This will create a new file inside app/Http/Requests directory. First of all, we need to return truefrom authorize method. We should write our validation logic inside the rules method. Also, we can customize the error message to whatever we want them to display on the front-end.

The above validation logic that was inside the controller is moved to respective request file. Thus, our validation file looks like below.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'    => 'required',
            'email'   => 'required|email',
            'phone'   => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'subject' => 'required',
            'message' => 'required'
        ];
    }

    /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.required'    => 'Name is required',
            'email.required'   => 'Email is required',
            'email.email'      => 'Email must be a valid email',
            'phone.required'   => 'Phone is required',
            'subject.required' => 'Subject is required',
            'message.required' => 'Message is required'
        ];
    }
}

Now, to validate form data using these rules, we must use the Form request. We should type-hint the Form request inside controller’s method.

<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactFormRequest;  //import the request
use Illuminate\Http\Request;

class ContactController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ContactFormRequest $request)
    {
        // data validated. proceed with data
        // continue with the data
    }
}

This is all about data validation in Laravel. Don’t forget to drop your thoughts in the comment below.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.