How to validate form request with laravel

  • July 25, 2021
  • 2337

Việc validate dữ liệu truyền vào là vô cùng quan trọng, nó giống như lớp thành trì bên ngoài để bảo vệ ứng dụng của bạn. Hôm nay chúng ta cùng tìm hiểu các validation hay dùng trong laravel nhé. Cách tốt nhất để validate input với laravel là sử dụng form request, giờ cùng tìm hiểu làm thế nào để validate input sử dụng form request với laravel ngay thôi.

Creating Form Requests

Tạo 1 form request bằng cách sử dụng command


php artisan make:request StoreUserRequest

khi chạy xong command file StoreUserRequest.php sẽ được tạo ra trong thư mục app/Http/Requests

How to use form request in laravel

Tìm hiểu ý nghĩa các hàm hay dùng trong form request của laravel, với form request bạn có thể hạn chế request, filter and validate request theo các rule... Bây giờ cùng tìm hiểu StoreUserRequest.php xem sao


<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Contracts\Validation\Validator;
use Exception;

class StoreUserRequest 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 [
            'username' => 'required|string|max:20|unique:users',
            'fullname' => 'nullable|string|max:50',
            'email' => 'required|email|max:50',
            'password' => 'required|string|max:20|min:6',
            'password_confirmation' => 'required|same:password',
        ];
    }

    /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            'email.required' => 'Email is required'
        ];
    }

    /**
     * Custom attribute for validation
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'email' => 'email address',
        ];
    }

    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->merge([
            'email' => is_string($this->email)
? Str::lower($this->email) : $this->email, 'username' => is_string($this->username)
? Str::lower($this->username) : $this->username, ]); } /** * Handle a failed validation attempt. * * @param Validator $validator * @return void */ protected function failedValidation(Validator $validator) { throw new Exception($validator->errors()->first(), Response::HTTP_UNPROCESSABLE_ENTITY); } /** * Configure the validator instance. * * @param Validator $validator * @return void */ public function withValidator(Validator $validator) { $validator->after(function ($validator) { if ($this->checkNameIsInvalid($this->username)) { $validator->errors()->add('username_invalid', 'Username is invalid!'); } }); } /** * Check username is invalid. * * @param Validator $validator * @return void */ private function checkNameIsInvalid($username) { if ($username === 'huunv') { return true; } return false; } }

1. Hàm authorize


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

Xác định xem request này có quyền được thực thi hay không? nếu hàm trả về true thì request có thể thực thi, thứ tự các hàm được gọi để validate prepareForValidation(), withValidator(), rules(), failedValidation()... nếu hàm trả về false request không có quyền thực thi, throw exception Illuminate\Auth\Access\AuthorizationException dựa vào nó để trả về http code 403(Forbidden). Request bị cấm không được thực thi

2. Hàm prepareForValidation

Hàm này thường được dùng để chỉnh sửa, filter input data trước khi data được validate bởi hàm rule(), ở vd trên nếu người dùng nhập vào username, email là chữ hoa thì sẽ được convert sang chữ thường.

3. Hàm withValidator

Hàm withValidator() được gọi sau hàm prepareForValidation() và được gọi trước các validation trong hàm rule(), hàm này có đối số là Illuminate\Contracts\Validation\Validator có thể định nghĩa field error và message error trong hàm này. còn hàm prepareForValidation thì không thể. Hàm này được sử dụng khi có một rule phức tạp không thể khai báo được bằng cách sử dụng rule method

4. Hàm rules

Hàm rules là trái tim của form request, các rule validation được khai báo ở đây, hàm được thực thi sau hàm prepareForValidation() và hàm withValidator().

5. Hàm messages

Hàm message được gọi sau hàm rules(), dùng để customer lại mesage trả về cho người dùng

6. Hàm attributes

Hàm attributes được gọi sau hàm mesages(), dùng để chỉnh sửa lại attribute, khi show error message, ở VD trên khi nhập sai email attribute email được thay thế bằng email address


Befor:
The email must be a valid email address.

After:
The email address must be a valid email address.

7. failedValidation

Hàm failedValidation được gọi khi người dùng nhập dữ liệu đầu vào không phù hợp với các rules khai báo trong hàm rules(), có thể sử dụng hàm này để throw exception khi validate lỗi, exception sẽ được catch trong hàm render() App/Exceptions/Handler.php


public function render($request, Throwable $e)
{
dd($e);
}

Validation with form request in laravel

Để validate dữ liệu người dùng nhập(input data) chỉ việc type-hint form request class UserStoreRequest vào hàm trong controller, UserStoreRequest sẽ tự động được gọi và vailidate input trước khi hàm trong controller được gọi.


<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserStoreRequest;

class UserController extends Controller
{
    public function store(UserStoreRequest $request)
    {
        $params = $request->all();
    }
}

Như vậy là chúng ta đã custom và validate dữ liệu người dùng nhập vào, đây là kết quả khi validate thành công nhé. Hi vọng bài viết sẽ giúp ích cho mọi người. Thanks for reading...