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

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...

Amazon S3 Pre-Signed URL with DropzoneJs in Laravel

Amazon S3 Pre-Signed URL with DropzoneJs in Laravel

Chức năng upload file hay hình ảnh là một chức năng rất phổ biến, hầu hết các dự án đều có chức năng này. Đa số các nhà phát triển khi thực hiện chức năng upload file, thường sẽ sử dụng cách làm nh...

Laravel Custom Rules

Laravel Custom Rules

Trong quá trình phát triển website Laravel, mình cảm thấy hệ thống Validation của Laravel rất tuyệt vời, nó cung cấp đã cung cấp cho chúng ta một bộ quy tắc kiểm tra dữ liệu, mà trong các trường hợp b...

Csv import with Validation for Laravel

Csv import with Validation for Laravel

Trong một bài viết lúc trước, mình đã chia sẻ đến các bạn cách xây dựng một service import và export CSV sử dụng Facades, nếu có bạn nào không biết hoặc đã quên các bạn có thể tham khảo lại bài viết t...

Laravel Routing

Laravel Routing

Route là gì? Đúng như tên gọi của nó, Route thực hiện chức năng định tuyến, dẫn đường cho các HTTP request gửi đến đúng nơi mà ta mong muốn. Với sự phát triển mạnh mẽ của ứng dụng web ngày nay, việc...

Integrating OpenAI in Laravel

Integrating OpenAI in Laravel

OpenAI OpenAI là một phòng thí nghiệm nghiên cứu trí tuệ nhân tạo (AI) của Mỹ bao gồm tổ chức phi lợi nhuận OpenAI Incorporated (OpenAI Inc.) và công ty con hoạt động vì lợi nhuận OpenAI Limited Par...

Send Slack Notifications In Laravel

Send Slack Notifications In Laravel

Slack là gì? Slack là một công cụ giao tiếp tại nơi làm việc, "một nơi duy nhất cho các tin nhắn, công cụ và file." Điều này có nghĩa là Slack là một hệ thống nhắn tin tức thì với nhiều plug-in cho...

Laravel  Scout Full Text Search with Algolia

Laravel Scout Full Text Search with Algolia

Laravel Scout cung cấp một giải pháp đơn giản, dựa trên trình điều khiển để thêm tìm kiếm Full Text vào các mô hình Eloquent của bạn. Khi sử dụng Eloquent, Scout sẽ tự động giữ chỉ mục tìm kiếm của bạ...

Laravel Factories, Seeder

Laravel Factories, Seeder

Trong bài viết này, tôi sẽ hướng dẫn các bạn về cách tạo dữ liệu giả trong cơ sở dữ liệu bằng cách sử dụng Laravel Factory và Seed trong Database Seeder. Để tạo model factory, bạn cần chạy lệnh sau...

ManhDanBlogs