Home > Net >  How To Get Laravel Controller Method Name & Method Type Automatically
How To Get Laravel Controller Method Name & Method Type Automatically

Time:07-04

Basically I'm calling an event every time a Controller method runs:

public function destroy(User $user)
{
   event(new AdminActivity('admin.users.destroy',class_basename(Route::current()->controller),'destroy','DELETE'));

   ...
}

In fact it is saving this information:

event(new AdminActivity(ROUTE_NAME,CONTROLLER_NAME,CONTROLLER_METHOD_NAME,CONTROLLER_METHOD_TYPE));

Now instead of passing parameters manually, I want to pass the required parameters automatically.

So I need to get route name, controller method name and controller method type auto (just like the class_basename(Route::current()->controller) which returns the controller name).

So how can I do that ?

CodePudding user response:

You can pass Route::current() to the event and then get your required information from the object of \Illuminate\Routing\Route

public function destroy(User $user)
{
   event(new AdminActivity(\Illuminate\Support\Facades\Route::current()));

   ...
}

Then, in your AdminActivity event class

class AdminActivity
{
    public function __construct(\Illuminate\Routing\Route $route)
    {
        $controllerClass  = class_basename($route->getController());
        $controllerMethod = $route->getActionMethod();
        $routeName        = $route->getAction('as');
        $methods          = $route->methods();
    }
}

Notice: return type of $route->methods() is an array that contains all valid request methods (GET, HEAD, POST, ...)

  • Related