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

Laravel One to Many Eloquent Relationship

Laravel One to Many Eloquent Relationship

One to Many Relationship được sử dụng trong trường hợp một dữ liệu của một bảng được liên kết với một hoặc nhiều dữ liệu ở bảng khác. Ví dụ, một bài post có thể có nhiều comment. Vì vậy, trong hướn...

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

Laravel Queues and Jobs

Laravel Queues and Jobs

Các công ty có thẻ gặp khó khăn trong việc quản lý các dịch vụ hoặc ứng dụng của họ. Ví dụ, các công ty các thực hiện gửi email cho hàng triệu người dùng hoặc thực hiện sao lưu dữ liệu. Tất cả các hoạ...

Laravel View

Laravel View

View là gì? Đây là phần giao diện (theme) dành cho người sử dụng. Nơi mà người dùng có thể lấy được thông tin dữ liệu của MVC thông qua các thao tác truy vấn như tìm kiếm hoặc sử dụng thông qua các...

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

Laravel Has Many Through Eloquent Relationship

Laravel Has Many Through Eloquent Relationship

Has Many Through Relationship hơi phức tạp để hiểu một cách đơn giản, nó sẽ cung cấp cho chúng ta một con đường tắt để có thể truy cập dữ liệu của một quan hệ xa xôi thông qua một mối quan hệ trung gi...

Laravel Logging Of Database Queries

Laravel Logging Of Database Queries

Laravel là một Framework PHP mạnh mẽ và linh hoạt, giúp cho việc phát triển ứng dụng trở nên đơn giản và dễ dàng hơn. Một trong những tính năng hữu ích của Laravel là khả năng ghi nhật ký truy vấn...

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

Simplify Your Laravel Workflow with Laravel Pint

Simplify Your Laravel Workflow with Laravel Pint

Laravel Pint là gì? Laravel Pint là một công cụ sửa đổi mã nguồn của bạn để mã nguồn của bạn tuân thủ theo các tiêu chuẩn. Nói một cách khác, Laravel Pint sẽ quét toàn bộ mã nguồn của bạn, phát...

ManhDanBlogs