Home PHP Framework Laravel A smart way to handle request validation in Laravel

A smart way to handle request validation in Laravel

Sep 20, 2019 am 09:41 AM
laravel

A smart way to handle request validation in Laravel

Laravel is the PHP framework for Web Craftsman. This helps us build powerful applications and APIs. As many of you know there are many ways to validate requests in Laravel. Handling request validation is a very important part of any application. Laravel has some great features that handle this problem very well.

Getting Started

Most of us are familiar with using validators in controllers. This is the most common way to handle validation of incoming requests.

Here is what our validator looks like UserController

<?php
namespace App\Http\Controllers\API\v1\Users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Entities\Models\User;
class UserController extends Controller
{
    public function store(Request $request)
    {
        // validate incoming request
        $validator = Validator::make($request->all(), [
           &#39;email&#39; => &#39;required|email|unique:users&#39;,
           &#39;name&#39; => &#39;required|string|max:50&#39;,
           &#39;password&#39; => &#39;required&#39;
       ]);
       if ($validator->fails()) {
            Session::flash(&#39;error&#39;, $validator->messages()->first());
            return redirect()->back()->withInput();
       }
       // finally store our user
    }
}
Copy after login

Validating in the controller

There is no problem validating the incoming request in the controller , but this is not the best approach and your controller will look messy. In my opinion this is bad practice. The controller should only handle one processing request from the route and return an appropriate response.

Writing validation logic in the controller will break the single responsibility principle. We all know that requirements change over time, and every time the requirements change, so will your class responsibilities. Therefore, having a lot of responsibilities in a single class makes management very difficult.

Laravel has form requests, a separate request class that contains validation logic. To create one, you can use the Artisan command.

php artisan make: Request UserStoreRequest

This will create a new Request class 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 [
            &#39;email&#39; => &#39;required|email|unique:users&#39;,
            &#39;name&#39; => &#39;required|string|max:50&#39;,
            &#39;password&#39; => &#39;required&#39;
        ];
    }
     /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            &#39;email.required&#39; => &#39;Email is required!&#39;,
            &#39;name.required&#39; => &#39;Name is required!&#39;,
            &#39;password.required&#39; => &#39;Password is required!&#39;
        ];
    }
}
Copy after login

Laravel Form Request class has two default methods auth( ) and rules(). You can perform any authorization logic in the auth() method regardless of whether the current user is allowed to request. In the rules() method you can write all the validation rules. There is also a method messages() to pass your own array of validation messages.

Now change our UserController to use our UserStoreRequest. You can enter the prompt for our request class and it will automatically parse and validate before calling our controller function.

<?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();
    }
}
Copy after login

So our controller is now slim and easy to maintain. Now our controller doesn't need to worry about any validation logic. We have our own validation class with only one responsibility to handle validation and let the controller work there.

If verification fails, it will redirect the user to the previous location and display an error. Depending on your request type an error message will flash in the session. If the request is AJAX, a response will be returned with a 422 status code and a JSON-formatted error.

Return

Keep your application and users safe by sanitizing input. Use a cleaner in your application and it will ensure that the data is always well-formatted and consistent. In many cases, validation fails due to silly formatting errors.

The mobile phone number entered by the user is 99-9999-999999 or 99-(9999)-(999999). This is a very common mistake and we cannot force our users to re-enter the same details again.

Some other examples are if the user enters an email as Foo@Bar.COM or FOO@Bar.com. Or enter first and last name, like FOO **bAR or foo baR**

Sanitizer Contains methods to transform and filter data in a common format before feeding it to the validator.

I'm using the Waavi/Sanitizer package which contains many filters.

Waavi / Data Cleaning

Let us create abstract class BaseFormRequest for Form Request and use SanitizesInput trait here.

<?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();
}
Copy after login

So now we can write the following content of UserStoreRequest. Extend your form requests from our base class so we don't have to include traits 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 [
            &#39;email&#39; => &#39;required|email|unique:users&#39;,
            &#39;name&#39; => &#39;required|string|max:50&#39;,
            &#39;password&#39; => &#39;required&#39;
        ];
    }
    public function messages()
    {
        return [
            &#39;email.required&#39; => &#39;Email is required!&#39;,
            &#39;name.required&#39; => &#39;Name is required!&#39;,
            &#39;password.required&#39; => &#39;Password is required!&#39;
        ];
    }
    /**
     *  Filters to be applied to the input.
     *
     * @return array
     */
    public function filters()
    {
        return [
            &#39;email&#39; => &#39;trim|lowercase&#39;,
            &#39;name&#39; => &#39;trim|capitalize|escape&#39;
        ];
    }
}
Copy after login

SanitizesInputtrait provides a filters() method to format our request data before providing it to the validator. The filters() method returns an array of valid filters. Here we convert the user email to lowercase and trim the same way we converted the name to uppercase and escape any HTML tags.

You can learn more about the available filters here.

Conclusion

First of all, it seems that there is no need to make separate request classes for everyone. But imagine putting all validation logic in the same controller. It's like a bad nightmare - when it comes to managing your code, how much worse is it if someone else has to manage it? .

Thank you for reading.

I'd like to hear your opinion on this. If you have any questions or suggestions, please leave a comment below.

Have a nice day.

For more Laravel related technical articles, please visit the Laravel Framework Getting Started Tutorial column to learn!

The above is the detailed content of A smart way to handle request validation in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel - Pagination Customizations Laravel - Pagination Customizations Aug 27, 2024 am 10:51 AM

Laravel - Pagination Customizations - Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatical

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

See all articles