Quay lại

Custom validation rules và messages trong Laravel form requests Chuyên mục PHP và Laravel    2023-08-02    164 Lượt xem    70 Lượt thích    comment-3 Created with Sketch Beta. 0 Bình luận

Custom validation rules và messages trong Laravel form requests

Nếu bạn muốn validate request fields  trong Laravel, bạn có thể sử dụng phương thức xác thực của Illuminate\Http\Request nơi bạn có thể chỉ định tất cả các trường mà bạn muốn validate  bên trong actions của controller’s . Bạn có thể làm như này.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
            'author.name' => 'required',
        ]);

        // The blog post is valid...
    }
}

Như bạn có thể thấy, chúng ta đã chỉ định các quy tắc validate trên các fields title và body và cho đến khi các quy tắc validate này khớp với nhau, request sẽ không được xử lý nữa

Nhưng vấn đề ở đây là controller action có thể nhanh chóng trở nên cồng kềnh nếu có nhiều fields mà bạn muốn validate. Làm thế nào bạn có thể làm cho nó sạch hơn và đẹp hơn một chút?

Sử dụng FormRequest class

Bạn có thể làm điều này bằng cách sử dụng Illuminate\Foundation\Http\FormRequest, về cơ bản là một request class tùy chỉnh chứa logic validation khi được extends .

Trước hết, bạn sẽ cần tạo một form request class. Để làm như vậy, bạn sẽ cần chạy artisan sau.

php artisan make:request PostRequest

Khi chạy lệnh trên, PostRequest sẽ được tạo trong app/Http/Requests extends  Illuminate\Foundation\Http\FormRequest. Đây là cách PostRequest sẽ trông như thế nào.

<?php

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

Để thêm các validation rules, bạn cần ghi đè phương thức rules() như vậy.

<?php

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
            'author.name' => 'required',
        ];
    }
}

Bây giờ, bạn có thể thay thế Request bằng PostRequest trong controller, trong ví dụ đầu tiên của bài viết là như này.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\PostRequest;

class PostController extends Controller
{
    /**
     * Store a new blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(PostRequest $request)
    {
        // The blog post is valid...
    }
}

Như bạn có thể thấy, chúng ta đã xóa validation tùy chỉnh khỏi controller’s action , chúng ta đang sử dụng PostRequest để xây dựng đối tượng $request, đối tượng này cuối cùng sẽ xử lý việc validation các fields request mà chúng ta đã thiết lập. Hành động bây giờ rõ ràng hơn và ít cồng kềnh hơn!

Tùy chỉnh Validation Messages

Ngoài việc thiết lập các quy tắc validation, bạn cũng có thể tùy chỉnh các thông báo validation trong form request classes. Đối với điều này, bạn sẽ cần ghi đè phương thức messages() như này.

<?php

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    public function rules()
    {
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
            'author.name' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'title.reuired' => 'A nice title is required for the post.',
            'body.required' => 'Please add content for the post.',
        ];
    }
}

Và khi validating các trường title và body, các messages được chỉ định trong các messages() sẽ được hiển thị thay vì các thông báo validating mặc định của Laravel.

 
 

Bình luận (0)

Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough

Bài viết liên quan

Learning English Everyday