Nếu bạn có một form để người dùng nhập dữ liệu và bạn muốn kiểm tra dữ liệu đầu vào trước khi lưu xuống database chẳng hạn thì bạn có 2 cách sau đây:

Cách 1: Bạn thêm validate trực tiếp vào hàm store hoặc update bạn có thể xem lại bài viết này.

Cách 2: Bạn tạo một class request riêng để kiểm tra dữ liệu.

Cá nhân mình thì mình sẽ chọn cách 2 vì điều này giúp cho controller trở nên sạch hơn một chút và các quy tắc kiểm tra dữ liệu sẽ nằm ở một nơi.

Bây giờ, chúng ta sẽ bắt đầu tìm hiểu cách hoạt động của nó như thế nào thông qua ví dụ sau đây.

Giả sử, chúng ta sẽ tạo một form gồm có những thông tin title và body.

Đầu tiên, chúng ta cần tạo một controller mới bằng lệnh command sau đây:

php artisan make:controller PostController

Tiếp theo, chúng ta cần phải tạo mới một route có url là "/post" có 2 method là get và post, bạn mở file routes/web.php và chỉnh sửa như sau:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('post', [PostController::class, 'create'])->name('posts.create');
Route::post('post', [PostController::class, 'store'])->name('posts.store');

Tiếp theo, chúng ta sẽ tạo ra class request có tên là StorePostRequest bằng lệnh command sau đây:

php artisan make:request StorePostRequest

Sau khi lệnh command trên chạy xong, nó tạo ra file StorePostRequest.php nằm trong thư mục app/Http/Requests, bạn hãy mở file StorePostRequest.php và chỉnh sửa như sau:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class  StorePostRequest 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 [
            'title' => 'required|max:255',
            'body'  => 'required',
        ];
    }
}

Tiếp theo, chúng ta sẽ sử dụng class request vừa mới tạo ở controller như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\StorePostRequest;

class PostController extends Controller
{
    public function create()
    {
        return view('post');
    }

    function store(StorePostRequest $request)
    {
        // store your post data
    }
}

Bây giờ, chúng ta hãy tạo file post.blade.php trong thư mục resources/views

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>Laravel Validation ManhDanBlogs</h2>
        <form method="post">
            @csrf
            @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
            <div class="form-group">
                <label for="title">Title:</label>
                <input type="text" class="form-control" name="title" value="{{ old("title") }}">
            </div>
            <div class="form-group">
                <label for="pwd">Body:</label>
                <textarea class="form-control" name="body">{{ old("body") }}</textarea>
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
    </div>
</body>
</html>

Đoạn mã dưới đây dùng để hiển thị các thông báo lỗi

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Bây giờ, bạn hãy nhìn tổng quan thì mã nguồn của chúng ta đẹp hơn rồi phải không?

Customization Class Request

Custom Messages

Bây giờ, điều gì sẽ xảy ra nếu bạn muốn thay đổi các thông báo của class request?

Thật dễ dàng để thực hiện với hàm messages() trong class request. Bạn chỉ cần xác định một mảng, trong đó key là tên field và value là thông bào bạn muốn thay đổi

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class  StorePostRequest 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 [
            'title' => 'required|max:255',
            'body'  => 'required',
        ];
    }
    /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        return [
            "title.required" => "Please write a title",
            "title.max"      => "The title has to have no more than :max characters.",
            "body.required"  => "Please write some content",
        ];
    }
}

Special Naming for Attributes

Như bạn đã biết, Laravel sẽ tự động tạo ra các câu thông báo validation. Vì vậy, đôi khi chúng ta cần cung cấp các tên đặc biệt cho các thuộc tính của mình. Bạn có thể sử dụng hàm attributes để thay đổi tên các thuộc tính để hiển thị những câu thông báo thân thiện hơn với người dùng, trong đó key là tên field, value là tên field mà bạn muốn thay thế.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class  StorePostRequest 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 [
            'title' => 'required|max:255',
            'body'  => 'required',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
             "body" => "Another Name",
        ];
    }
}

Tôi hy vọng bạn thích hướng dẫn này. Nếu bạn có bất kỳ câu hỏi nào hãy liên hệ với chúng tôi qua trang contact. Cảm ơn bạn.

CÓ THỂ BẠN QUAN TÂM

Laravel Upload File Using Trait

Laravel Upload File Using Trait

Hiện nay, đa số các dự án đều có chức năng upload file, nên tôi đã thử xây dựng một lớp Trait Upload File, để chúng ta dễ dàng sao chép qua các dự án khác để sử dụng, nhằm rút ngắn thời gian phát triể...

Laravel UI Custom Email Verification Template

Laravel UI Custom Email Verification Template

Nếu bạn đang dùng thư viện laravel/ui để làm các chức năng liên quan đến authentication, và trong dự án của bạn, bạn cần thay đổi template email verification thay vì sử dụng template email verificatio...

Integrating CKEditor 5 in Laravel 10 using Vite

Integrating CKEditor 5 in Laravel 10 using Vite

CKEditor 5CKEditor 5 là một trình soạn thảo văn bản phong phú JavaScript với nhiều tính năng và khả năng tùy chỉnh. CKEditor 5 có kiến trúc MVC hiện đại, mô hình dữ liệu tùy chỉnh và DOM ảo, mang...

Integrating elFinder into TinyMCE 6 in Laravel

Integrating elFinder into TinyMCE 6 in Laravel

TinyMCE TinyMCE là một trình soạn thảo WYSIWYG được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép MIT bởi Tiny Technologies Inc. TinyMCE cho phép người d...

Laravel Migration

Laravel Migration

Migration cho phép các nhà phát triển (Developer) nhanh chóng tạo ra cở sở dữ liệu của ứng dụng mà không cần vào màn hình quản lý cơ sở dữ liệu hay chạy bất kì một câu lệnh SQL nào. Trước hết, nếu...

Integrating CKFinder into CKEditor 5 in Laravel 11

Integrating CKFinder into CKEditor 5 in Laravel 11

CKEditor 5 CKEditor 5 là một trình soạn thảo văn bản phong phú JavaScript với nhiều tính năng và khả năng tùy chỉnh. CKEditor 5 có kiến trúc MVC hiện đại, mô hình dữ liệu tùy chỉnh và DOM ảo, mang...

Laravel Artisan Console

Laravel Artisan Console

Ngoài các lệnh command mặc định của Laravel được cung cấp bởi Artisan, có rất nhiều tác vụ trong ứng dụng Laravel của bạn có thể được xử lý rất tốt bằng các lệnh command này. Nhưng đôi khi có nhiều tá...

Laravel Socialite Login With Linkedin

Laravel Socialite Login With Linkedin

LinkedIn LinkedIn là mạng xã hội tập trung vào mạng lưới nghề nghiệp và phát triển nghề nghiệp và chuyên nghiệp lớn nhất thế giới trên internet. Bạn có thể sử dụng LinkedIn để tìm công việc hoặc...

Implementing Private User Folders with CKFinder in Laravel

Implementing Private User Folders with CKFinder in Laravel

CKFinder 3 CKFinder 3 là trình quản lý tập tin được tích hợp với CKEditor 4 và CKEditor 5. Nó giúp bạn dễ dàng đưa các tập tin và hình ảnh vào nội dung của Editor một cách an toàn. Đây là một tín...

ManhDanBlogs