Return callback based on route name in Laravel

I searched the internet a lot, but couldn't find a solution.

I need to return the callback registered on a route, based on the route name.


Example

My routes/api.php:

Route::get('test', 'TestController@test')->name('test');

That is, based on the example above, I want to capture the string TestController@test, stating that the route is 'test'.

It is possible?

Can someone help me?

Thank you in advance for your attention.

Upvotes: 0

Views: 763

Answers (2)

lagbox
lagbox

Reputation: 50531

You can use getActionName() or getAction('controller') on a Route instance to get this information. You will get a FQCN. To get just the last part you can use class_basename():

$route = Route::getRoutes()->getByName('test');

$action = $route->getActionName();
// 'App\Http\Controllers\TestController@test'

$basename = class_basename($action); 
// 'TestController@test'

// all together now
class_basename(Route::getRoutes()->getByName('test')->getActionName());

Upvotes: 2

Salim Djerbouh
Salim Djerbouh

Reputation: 11044

If you want to get just the TestController@test you may do so like this

substr(strrchr(Route::getRoutes()->getByName('test')->action['uses'], '\\'), 1);

Hope it helps

Upvotes: 2

Related Questions