How to automatically get Laravel controller method name and method type
P粉573809727
P粉573809727 2024-02-26 13:54:16
0
1
377

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粉573809727
P粉573809727

reply all(1)
P粉616383625

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...)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!