Truy cập route hiện tại (phần 2)

Truy cập route hiện tại (tiếp tục)

Hãy nhìn vào một vài ví dụ nơi chúng ta có thể truy cập route hiện tại trong một ứng
dụng Laravel.
Giả sử chúng ta có các routes sau được định nghĩa trong file routes/web.php của chúng ta:

Route::get( ‘/home’ , function () {
return view( ‘home’ );
})->name( ‘home’ );
Route::get( ‘/about’ , function () {
return view( ‘about’ );
})->name( ‘about’ );
Route::get( ‘/posts/{post}’ , [PostController::class,
‘show’ ])->name( ‘posts.show’ );

Ví dụ 1: Truy cập route hiện tại bên trong một phương thức controller.

use Illuminate \ Support \ Facades \ Route ;
public function show ($id)
{
$route = Route::current(); // Get the current route.
$name = Route::currentRouteName(); // Get the name
of the current route.
$action = Route::currentRouteAction(); // Get the
controller action of the current route.
// Now you can use $route, $name, or $action in
your controller logic.
// …
}

Ví dụ 2: Hiển thị tên route hiện tại trong một view. Bạn có thể sử dụng cách tiếp cận này để nêu
bật page hiện tại trong một thanh điều hướng.
Trong Blade view file của bạn:

<ul>
<li class =”{{ Route::currentRouteName() == ‘home’ ?
‘active’ : ” }} “>
<a href=” /home “>Home</a>
</li>
<li class=” {{ Route::currentRouteName() == ‘about’
? ‘active’ : ” }} “>
<a href=” /about “>About</a>
</li>
</ul>

Trong ví dụ ở trên, vật list cho route hiện tại sẽ có active class.
Ví dụ 3: Truy cập các tham số của route hiện tại.

use Illuminate \ Support \ Facades \ Route ;
public function show ($id)
{
$route = Route::current(); // Get the current route.
$parameters = $route->parameters(); // Get the
parameters of the current route.
// Now you can use $parameters in your controller
logic.
// …
}

Trong ví dụ này, $parameters sẽ là một mảng tương quan nơi các keys là các tên tham số và các values
các giá trị tham số. Cho ‘posts.show’ route, $parameters sẽ là thứ gì đó giống [‘post’ => 123] nếu
URL hiện tại là /posts/123.

Chia sẻ

Leave a Reply

Your email address will not be published. Required fields are marked *