search

Home  >  Q&A  >  body text

How to automatically get Laravel controller method name and method type

Basically, every time a controller method runs I call an event:

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 I want to automatically pass the required parameters instead of passing them manually.

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

So what should I do?

P粉573809727P粉573809727261 days ago421

reply all(1)I'll reply

  • P粉616383625

    P粉6163836252024-02-27 09:22:02

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

    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();
        }
    }
    

    Note: The return type of $route->methods() is an array, containing all valid request methods (GET, HEAD, POST...)

    reply
    0
  • Cancelreply