Plamen Vasilev
Plamen Vasilev

Reputation: 362

Get controller and action of route in Laravel

I want to resolve the controller name and action which are configured for a route

I have a route:

Route::get('/somePage','SomeController@someAction');

Can I get the controller name and action using something like:

resolve('/somepage');

to receive the same result which I can get from Route::current()->getActionName()

App\Http\Controllers\SomeController@someAction

Upvotes: 0

Views: 410

Answers (3)

levi
levi

Reputation: 25091

This should work:

function getAction($uri, $method) {
        $route = collect(Route::getRoutes())
            ->filter(function($route) use($uri, $method){
            return $route->getUri() === $uri && 
                    in_array($method, $route->getMethods());
        })->first();
        return $route ? $route->getAction() : null;
}

Usage:

$action = getAction('posts', 'GET');

Alternatively:

$request = \Illuminate\Http\Request::create('posts', 'GET');
$action = Route::getRoutes()->match($request)->getAction();

Upvotes: 5

Rakibul Islam
Rakibul Islam

Reputation: 687

Simply you can get controller name and action by this

request()->route()->getAction()

Upvotes: -1

David
David

Reputation: 165

I usually use route('somePageRoute') method but first name the route

Route::get('/somePage','SomeController@someAction')->name('somePageRoute');

Upvotes: 0

Related Questions