Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 18: URL trong Laravel 8

Laravel cung cấp cho chúng ta một helper function url, hàm này cho phép chúng ta tạo ra các links trên ứng dụng một cách đơn giản và linh hoạt. Phần này mình sẽ giới thiệu với mọi người một số feature liên quan đến URL trong Laravel 8.

1. Generate URL.

Để generate URL trong Laravel các bạn sử dụng hàm url, với cú pháp sau:

url($path, $parameters, $secure);

Trong đó:

  • $path là path mà bạn muốn generate.
  • $parameters là các param mà bạn muốn truyền vào URL. Tham số này có thể bỏ trống.
  • $secure là tham số quyết định protocol của URL là http hay https. Tham số này có thể bỏ trống.

VD:

url('home');
// http://example.com/home

url('home', ['page', 2]);
// http://example.com/home/page/2

url('home', ['page', 2], true);
// https://example.com/home/page/2

2. Truy cập URL hiện tại.

Để lấy ra URL hiện tại của request các bạn sử dụng phương thức current. Phương thức này sẽ trả về URL không bao gồm query string.

VD:

echo url()->current();

Trong trường hợp bạn muốn lấy ra URL bao gồm cả qurey string query string, bạn có thể sử dụng phương thức full.

VD:

echo url()->full();

Trong trường hợp bạn muốn lấy ra URL của request trước đó bao gồm cả query string, bạn có thể sử dụng phương thức previous.

VD:

echo url()->previous();

Tất cả các cách trên nếu bạn không muốn sử dụng helper, thì có thể thay thế bằng URL (Illuminate\Support\Facades\URL) facades.

VD:

echo URL::current();

echo URL::full();

echo URL::previous();

3. Route URL.

Trong trường hợp route của bạn có sử dụng route name. Các bạn có thể sử dụng hàm route để generate ra URL của route đó.

VD:

Route::get('post', function () {
    //
})->name('post.index');

echo route('post.index');

// http://example.com/post/

VD: Đối với route có parameter.

Route::get('/post/{post}', function () {
    //
})->name('post.show');

echo route('post.show', ['post' => 1]);

// http://example.com/post/1
Route::get('/post/{post}/comment/{comment}', function () {
    //
})->name('comment.show');

echo route('comment.show', ['post' => 1, 'comment' => 3]);

// http://example.com/post/1/comment/3

Trong trường hợp các param truyền vào hàm route không xuất hiện trong route đó thì những tham số đó sẽ được chuyển về dạng query string.

VD:

Route::get('/post/{post}', function () {
    //
})->name('post.show');

echo route('post.show', ['post' => 1, 'search' => 'rocket']);

// http://example.com/post/1?search=rocket

4. Signed URL.

Laravel cho phép chúng ta tạo ra một dạng URL kèm theo một tham số Laravel gọi nó là "signature". Khi một route sử dụng chức năng này thì cần implement thêm middleware "signed", để check, nếu như chũ ký sai thì Laravel sẽ trả về http status là 403.

VD:

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;

Route::get('home', function () {
    return 'home';
})->name('home')->middleware('signed');

echo URL::signedRoute('home');

// http://example.com/home?signature=d2f00428a23f6aae7f365dbbdb69f45a0a69633a1943e287abd7d16df6566da8

Trong trường hợp mà bạn không muốn sử dụng middleware "signed" mà vẫn muốn kiểm tra signature có đúng hay không. Bạn có thể sử dụng phương thức hasValidSignature trong Request.

VD:

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

Route::get('home', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }

    return 'home';
})->name('home');

echo URL::signedRoute('home');

// http://example.com/home?signature=d2f00428a23f6aae7f365dbbdb69f45a0a69633a1943e287abd7d16df6566da8

Trong một số trường hợp bạn muốn tạo ra một signed URL chỉ tồn tại trong một khoảng thời gian nhất định nào đó. Bạn có thể sử dụng phương thức temporarySignedRoute với cú pháp:

URL::temporarySignedRoute($routeName, $timeToLive, $parameters);

Trong đó:

  • $routeName là tên của route các bạn muốn generate URL.
  • $timeToLive là thời gian sống của URL.
  • $parameters là các param mà bạn muốn truyền vào URL.

VD: Mình sẽ tạo ra temporarySignedRoute cho route home và thời gian sống mình sẽ xét là 2 tiếng.

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

Route::get('home', function (Request $request) {
    if (! $request->hasValidSignature()) {
        abort(401);
    }
    return 'home';
})->name('home');

Route::get('/', function () {
    return URL::temporarySignedRoute('home', now()->addHours(2));
});

// http://127.0.0.1:8000/home?expires=1610708830&signature=2010579f38999eca041cfb1b63c29355531ad0c318b19605f27ec8ccd68eeb65

5. Controller Action URL.

Bạn cũng có thể tạo ra URL thông qua controller action bằng cách sử dụng hàm action.

VD:

use App\Http\Controllers\HomeController;

$url = action([HomeController::class, 'index']);

Tương tự với trường hợp cần truyền thêm param vào trong action bạn có thể truyền thêm tham số thứ 2 vào trong hàm action với cú pháp, chức năng tương tự như hàm route.

VD:

$url = action([UserController::class, 'profile'], ['id' => 1]);

6. Default Value.

Trong một số trường hợp, các bạn muốn gán giá trị mặc định cho một parameter nào đó các bạn có thể sử dụng phương thức default.

VD:

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

URL::defaults(['locale' => 'vi']);

Route::get('{locale}/about/', function (Request $request) {
    return 'about';
})->name('about');

Route::get('/', function () {
    return route('about');
});

Các bạn cũng có thể đưa URL::defaults(['locale' => 'vi']); vào trong middleware, để thực thi các logic cần thiết để lấy ra locale.

VD: Mình sẽ tạo middleware SetDefaultLocaleForUrls và đưa logic vào trong đó.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Illuminate\Http\Response
     */
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale' => $request->user()->locale]);

        return $next($request);
    }
}

Tuy nhiên khi khai báo middleware thì các bạn cần phải khai báo mức độ ưu tiên sao cho middleware của các bạn phải thực thi trước middleware SubstituteBindings.

VD: file app/Http/Kernel.php.

/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [
    // ...
     \App\Http\Middleware\SetDefaultLocaleForUrls::class,
     \Illuminate\Routing\Middleware\SubstituteBindings::class,
    // ...
];

7. Lời kết.

Url generation trong Laravel của thực rất hữu dụng. Sau này mọi người sẽ sử dụng nó nhiều đó.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha