+3

Laravel `prepareForValidation()` tiền xử lý yêu cầu (request) trước khi xác thực (validate)

Method prepareForValidation() trong Illuminate\Foundation\Http\FormRequest giúp bạn tiền xử lý yêu cầu (request) trước khi xác thực (validate).

1. Đặt vấn đề

Giả sử trong lúc tạo 1 api lấy danh sách bài viết (post) bạn muốn để gán giá trị số bài viết trên trang mặc định là 20 (per_page = 20). Cơ bản, thông thường chúng ta sẽ gán ở Controller hoặc trong Model hoặc cả hai.

  • Controller

    // app/Models/Post.php
    
    /**
     * @param int $perPage
     * @return mixed
     */
    public function index(int $perPage = 20)
    {
        //...
    }
    
  • Model

    // app/Http/Controllers/PostController.php
    
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $posts = $this->model->index($request->get('per_page', 20));
        return response()->json($posts);
    }
    

Có 1 cách khác là các bạn có thể tiền xử lý trước ngay trong $request.

2. Method prepareForValidation()

  • Tạo một class PostRequest bằng câu lệnh dưới
    php artisan make:request PostRequest
    
  • Thêm method prepareForValidation() vào app/Http/Requests/PostRequest.php
    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->merge([
            'per_page' => $this->get('per_page', 20),
        ]);
    }
    
  • Bạn có thể ép kiểu luôn cho biến per_page để chắc chắn nó là 1 số nguyên
        /**
         * Prepare the data for validation.
         *
         * @return void
         */
        protected function prepareForValidation()
        {
            $this->merge([
                'per_page' => (int)$this->get('per_page', 20),
            ]);
        }
    

3. Áp dụng vào các bài toán thực tế

Trong các dự án thực tế mình thường hay dùng method này để:

  • Gán giá trị mặc định cho request (giống trường hợp phía trên)

  • Ép kiêu dữ liệu

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'is_active' => 'nullable|boolean',
            'per_page'  => 'nullable|integer',
        ];
    }
    
    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $catIds = $this->get('cat_ids', []);
        $this->merge([
            'is_active' => $this->boolean('is_active', false),
            'per_page' => (int)$this->get('per_page', 20),
        ]);
    }
    
  • Định dạnh lại dữ liệu cho request trước khi validate. Vd mình có API lấy danh sách bài viết (post) và muốn lọc theo ID danh mục (category ID). Có thể truyền cat_id dưới dạng chuỗi hoặc mảng đều được.

    // API [GET] /api/posts?cat_ids=1,2,3
    // API [GET] /api/posts?cat_ids=[1,2,3]
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        return [
            'cat_ids' => 'nullable|array'
        ];
    }
    
    /**
     * Prepare the data for validation.
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $catIds = $this->get('cat_ids', []);
        $this->merge([
            'cat_ids' => is_string($catIds) ? explode(',', $catIds) : $catIds,
        ]);
    }
    

4. Tham khảo

5. Lời kết

Trên website Laravel đã có đầy đủ hướng dẫn chi tiết về tất cả các phương thức mà laravel hỗ trợ ngoài ra còn có trang Laravel github source các bạn có thể đọc thêm cũng như thử nghiệm nhiều trường hợp để có thể sử dụng chúng một cách hiệu quả đúng trường hợp nhất nhé.

Hi vọng chia sẻ này sẽ giúp các bạn newbie 1 phần nào trong quá trình tìm hiểu về Laravel. Nếu thấy hữu ích hãy cho mình 1 vote 👍 để thêm nhiều người biết đến chia sẻ này nhé.

Mình là Công Thành cám ơn các bạn đa theo dõi bài viết của mình, nếu có câu hỏi nào vui lòng bình luận phía dưới 👇 nhé.

Xem thêm series bài viết 👉 Laravel tips


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí