Laravel How to get Route Profile based on Route Name

383 Views Asked by At

I have this route:

Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController@index'])

I've been tried to use $routeProfile=route('test'); But the result is returned url string http://domain.app/test

I need ['as'=>'test','custom_key'=>'custom_value'] so that I can get the $routeProfile['custom_key']

How can I get 'custom_value' based on route name ?

4

There are 4 best solutions below

1
On BEST ANSWER

For fastest way, now I use this for my question:

function routeProfile($routeName)
{
    $routes = Route::getRoutes();
    foreach ($routes as $route) {
        $action = $route->getAction();
        if (!empty($action['as']) && $routeName == $action['as']) {
            $action['methods'] = $route->methods();
            $action['parameters'] = $route->parameters();
            $action['parametersNames'] = $route->parametersNames();
            return $action;
        }
    }
}

If there's any better answer, I will be appreciate it. Thanks...

0
On

I believe you are looking for a way to pass variable to your route

Route::get('/test/{custom_key}',[
    'uses'=>'TestController@index',
    'as'=>'test'
]);

You could generate a valid URL like so using route('test',['custom_key'=>'custom_key_vale'])

In your view:

<a href="{route('test',['custom_key'=>'custom_key_vale'])}"

In your controller method:

....

public function test(Request $request)
{
   $custom_key = $request->custom_key;
}
....
0
On

You can try one of the below code:
1. Add use Illuminate\Http\Request; after namespace line code

public function welcome(Request $request)
{
    $request->route()->getAction()['custom_key'];
}

2. OR with a facade

Add use Route; after namespace line code

and use below into your method

public function welcome()
{
    Route::getCurrentRoute()->getAction()['custom_key'];
}

Both are tested and working fine!

0
On

Try this:

use Illuminate\Support\Facades\Route;

$customKey = Route::current()->getAction()['custom_key'];