Skip to content

Tạo URL (URL Generation)

Giới thiệu (Introduction)

Laravel cung cấp nhiều helpers để tạo URLs cho ứng dụng. Hữu ích khi xây dựng links trong templates và API responses, cũng như tạo redirect responses.

Cơ bản (The Basics)

Tạo URLs (Generating URLs)

Helper url tạo URLs tùy ý:

php
$post = App\Models\Post::find(1);

echo url("/posts/{$post->id}");
// http://example.com/posts/1

Gọi url không có tham số trả về instance Illuminate\Routing\UrlGenerator:

php
echo url()->current();       // URL hiện tại (không có query string)
echo url()->full();          // URL đầy đủ (có query string)
echo url()->previous();      // URL trang trước

Truy cập URL hiện tại

php
use Illuminate\Support\Facades\URL;

echo URL::current();
echo URL::full();
echo URL::previous();

URLs cho Named Routes

Helper route tạo URLs cho named routes:

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

echo route('post.show', ['post' => 1]);
// http://example.com/post/1

Parameters bổ sung tự động thêm vào query string:

php
echo route('post.show', ['post' => 1, 'search' => 'rocket']);
// http://example.com/post/1?search=rocket

Truyền Eloquent model — tự động extract key:

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

Signed URLs

Tạo "signed" URLs có hash xác minh, đảm bảo URL chưa bị sửa đổi:

php
use Illuminate\Support\Facades\URL;

return URL::signedRoute('unsubscribe', ['user' => 1]);

// Có thời hạn (temporary)
return URL::temporarySignedRoute(
    'unsubscribe', now()->addMinutes(30), ['user' => 1]
);

Xác minh signed URL trong request:

php
if (! $request->hasValidSignature()) {
    abort(401);
}

Hoặc gán middleware signed cho route:

php
Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
})->name('unsubscribe')->middleware('signed');

URLs cho Controller Actions

Helper action tạo URL cho controller action:

php
use App\Http\Controllers\HomeController;

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

// Với parameters
$url = action([UserController::class, 'profile'], ['id' => 1]);

Fluent URI Objects

Tạo và thao tác URI objects:

php
use Illuminate\Support\Uri;

$uri = Uri::of('https://example.com/path')
    ->withQuery(['sort' => 'date'])
    ->withFragment('section');
// https://example.com/path?sort=date#section

Từ named routes:

php
$uri = Uri::route('profile', ['user' => 1])
    ->withQuery(['tab' => 'posts']);

Giá trị mặc định (Default Values)

Đặt giá trị mặc định cho URL parameters (ví dụ: locale) bằng URL::defaults:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;

class SetDefaultLocaleForUrls
{
    public function handle(Request $request, Closure $next): Response
    {
        URL::defaults(['locale' => $request->user()->locale]);

        return $next($request);
    }
}

Sau khi đặt, không cần truyền locale mỗi khi tạo URL qua helper route.