How To Get Route Prefix In Blade File In Laravel

Hello devs,

In this example, I will show you how to get the current route prefix in the Laravel blade file. Sometimes we need to check the current route prefix name. You know that knowing the current route prefix name, we can make the menu item open for each group. 

In this scenario, we can use the route prefix name to do that. So if you don't know the Laravel get route prefix in the blade file then this example is for you. So let's see how we can get a route prefix in the Laravel application.

Assume this is our route with prefix:

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;

Route::prefix('admin')->group(function () {
    Route::get('/', [TestController::class,'index']);
});

 

Just use this code to get the route prefix name:

resources/views/test.blade.php

@php
   $prefix = Request::route()->getPrefix();
   $route = Route::current()->getName();
@endphp

{{ $prefix }}

 

Now if you run the code, it will return the output like:

 

output
/admin

 

Read also: How to Check Route Name Exists or Not in Laravel

 

Hope this laravel get route prefix in blade tutorial will help you.

 

#laravel #laravel-8x