Trong khuôn khổ của Laravel, các route của api được tách thành một file duy nhất, đó là file api.php nằm trong thư mục routes. Nếu chúng ta muốn thêm version vào route api thì chúng ta sẽ làm như sau:

Route::prefix('v1')->namespace('Api\V1')->group(function() {
    Route::resource('photos', 'PhotoController');
});

Route::prefix('v2')->namespace('Api\V2')->group(function() {
    Route::resource('photos', 'PhotoController');
});

Nhìn cách giải quyết trên thì không có vấn đề gì khi bạn dùng cho dự án nhỏ (không có quá nhiều route). Nhưng đối với các dự án lớn (có rất nhiều route) thì chúng ta sẽ phát hiện ra rằng khi có nhiều route và nhiều version nữa thì file api.php sẽ quá lớn để chúng ta quản lý.

Để giải quyết tình trạng trên chúng ta sẽ chia các version api thành các file khác nhau tương ứng với version đó.

Đầu tiên, chúng ta sẽ thực hiện thêm các function như mapApiVersionRoutes, getApiVersion, getApiNamespace vào file app\Providers\RouteServiceProvider.php để xác định các file version api. Sau khi chỉnh sửa nội dung file sẽ trông giống như sau:

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    ...

    protected $namespace = 'App\\Http\\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        ...
        $this->mapApiVersionRoutes();
    }

    ...

    protected function mapApiVersionRoutes()
    {
        $files = \File::allFiles(base_path('routes'));
        foreach ($files as $key => $file) {
            $basename = pathinfo($file)['basename'];
            if (preg_match("/api_v[0-9].php/", $basename)) {
                Route::prefix("api/v{$this->getApiVersion($basename)}")
                ->middleware('api')
                ->namespace($this->getApiNamespace($this->getApiVersion($basename)))
                ->group(base_path("routes/{$basename}"));
            }
        }
    }

    private function getApiVersion($basename)
    {
        return str_replace(["api_v", ".php"], "", $basename);
    }

    private function getApiNamespace($version)
    {
        if ($this->namespace) {
            return "{$this->namespace}\Api\V{$version}";
        }
        return "";
    }
}

Như vậy thôi, chúng ta đã setting xong chức năng auto map version api rồi, để hệ thống có thể tự động map api route được, chúng ta cần đặt tên file api theo format như sau:

Format: api_v{version}.php

Ví dụ: api_v1.php, api_v2.php,...

Để kiểm tra xem hệ thống map version api của chúng ta có hoạt động được hay không, đầu tiên chúng ta cần tạo ra hai controller để thử nghiệm bằng lệnh command sau:

php artisan make:controller Api\V1\PhotoController --resource
php artisan make:controller Api\V2\PhotoController --resource

Tiếp theo đó, chúng ta cần hai file route trong thư mục routes và có nội dung như sau:

routes\api_v1.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API V1 Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::resource('photos', PhotoController::class);

routes\api_v2.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API V2 Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::resource('photos', PhotoController::class);

Cuối cùng, chúng ta chạy lệnh command sau để xem các route api đã chia thành các version hay chưa:

php artisan roue:list

Kết quả:

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

Generate PDF with Header and Footer on every page in Laravel

Generate PDF with Header and Footer on every page in Laravel

Hôm nay, trong bài viết này mình sẽ chia sẻ với các bạn cách dompdf mà header và footer sẽ được hiển thị ở tất cả các trang. Đây cũng là một vấn đề khá phổ biến, khi chúng ta phát triển các tính năng...

Encrypted HTTP Live Streaming with Laravel FFMpeg

Encrypted HTTP Live Streaming with Laravel FFMpeg

HTTP Live Streaming (HLS)  HTTP Live Streaming (HLS) là một trong những giao thức phát trực tuyến video được sử dụng rộng rãi nhất . Mặc dù nó được gọi là HTTP "live" streaming, nhưng nó được sử dụn...

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 Mail Sending Redirector Listener

Laravel Mail Sending Redirector Listener

Trong quá trình phát triển web, việc gửi email là một chức năng quan trọng để thông báo, đặt lại mật khẩu, hoặc tương tác với người dùng. Tuy nhiên, khi chúng ta đang trong quá trình phát triển, vi...

Export CSV from SQL Server - Import into MySQL with Laravel

Export CSV from SQL Server - Import into MySQL with Laravel

Transfer Database Trong quá trình phát triển và bảo trì dự án, việc di chuyển cơ sở dữ liệu từ hệ thống này sang hệ thống khác là một nhiệm vụ khá phổ biến. Giả sử bạn cần di chuyển dữ liệu từ SQ...

Laravel One to Many Polymorphic Relationship

Laravel One to Many Polymorphic Relationship

One to Many Polymorphic Model Relationship được sử dụng khi một model thuộc về nhiều model khác trên một model kết hợp duy nhất. Ví dụ: Nếu chúng ta có bảng post và video, cả hai đều cần thêm hệ thống...

Laravel UI Password Reset Expired

Laravel UI Password Reset Expired

Trong thư viện laravel/ui, thì chức năng password reset dù cho token có hết hạn thì vẫn có truy cập vào trang password reset, đến khi bạn submit form thì mới thông báo là token đã hết hạn. Nhưng có 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...

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

ManhDanBlogs