How to use advance validation in laravel (The Smart Way)

Generic placeholder image
Brijpal Sharma
sql laravel  

Date:-September 10th, 2018 , Posted On:- Database


In this post, we are going to learn how to use advance validation in laravel. we use request method to validate data when user posts some data.

To every website, a validation function is required this function protect our website and also it helps to user to submit a right data on a website.

It is very important to the admin of a website to manage data record.

In this post, we learn Laravel advance validation function using the request method. So here we not going to use validation in a controller as usually. 

To create a request to use this flowing command.

php artisan make:request UserStoreRequest

A new file created in App\Http\Request\UserRequest 

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest 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 [
            'email' => 'required|email|unique:users',
            'name' => 'required|string|max:50',
            'password' => 'required'
        ];
    }
     /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            'email.required' => 'Email is required!',
            'name.required' => 'Name is required!',
            'password.required' => 'Password is required!'
        ];
    }
}

Laravel request has two methods auth() and rule(). we can perform any authorization logic in auth().  and all validation rule in rule() method. 

Now we change some code in controller UserController to UserStoreRequest.

 

<?php
namespace App\Http\Controllers\API\v1\Users;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserStoreRequest;
class UserController extends Controller
{
    public function store(UserStoreRequest $request)
    {
        // Will return only validated data
        
        $validated = $request->validated();
    }
}

Now we do not use validation code in the controller we have a separate file of validation.

If some cases validation fails, it will redirect the user to the previous location with an error message.

To keep data in format here we are using package Waavi/Sanitizere which has many filters.

Sanitizer has many methods for filtering and transforming our data in common format before providing to the validator.

First, create a BaseFormRequest class for our form request using Sanitizes.

<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Waavi\Sanitizer\Laravel\SanitizesInput;
abstract class BaseFormRequest extends FormRequest
{
    use ApiResponse, SanitizesInput;
    /**
     * For more sanitizer rule check https://github.com/Waavi/Sanitizer
     */
    public function validateResolved()
    {
        {
            $this->sanitize();
            parent::validateResolved();
        }
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    abstract public function rules();
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    abstract public function authorize();
}

So now we can add our in UserStoreRequest Form Request from our base class so we don’t have to include trait in all request classes.

<?php
namespace App\Http\Requests;
class UserStoreRequest extends BaseFormRequest
{
    /**
     * 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 [
            'email' => 'required|email|unique:users',
            'name' => 'required|string|max:50',
            'password' => 'required'
        ];
    }
    public function messages()
    {
        return [
            'email.required' => 'Email is required!',
            'name.required' => 'Name is required!',
            'password.required' => 'Password is required!'
        ];
    }
    /**
     *  Filters to be applied to the input.
     *
     * @return array
     */
    public function filters()
    {
        return [
            'email' => 'trim|lowercase',
            'name' => 'trim|capitalize|escape'
        ];
    }
}

SanitizesInput in best method for filters() for formatting our request data before submitting to the validator. after formatting, filter() method return of valid filtered array.


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

0 comments

You must be logged in to post a comment.