Get Laravel 5 controller name in view

后端 未结 4 1644
渐次进展
渐次进展 2020-12-03 14:02

Our old website CSS was set up so that the body tag had an id of the controller name and a class of the action name, using Zend Framework 1. Now we\'re switchi

相关标签:
4条回答
  • 2020-12-03 14:09

    I will simply use as bellow

    $request->route()->getActionMethod()
    
    0 讨论(0)
  • 2020-12-03 14:17

    If your layout is a Blade template, you could create a view composer that injects those variables into your layout. In app/Providers/AppServiceProvider.php add something like this:

    public function boot()
    {
        app('view')->composer('layouts.master', function ($view) {
            $action = app('request')->route()->getAction();
    
            $controller = class_basename($action['controller']);
    
            list($controller, $action) = explode('@', $controller);
    
            $view->with(compact('controller', 'action'));
        });
    }
    

    You will then have two variables available in your layout template: $controller and $action.

    0 讨论(0)
  • 2020-12-03 14:19

    I use a simple solution. You can test and use it in everywhere, also in your views:

    {{ dd(request()->route()->getAction()) }}
    
    0 讨论(0)
  • 2020-12-03 14:30

    To get something like PostController try following ...

    preg_match('/([a-z]*)@/i', $request->route()->getActionName(), $matches);
    $controllerName = $matches[1];
    

    $matches[1] includes the first group while $matches[0] includes everything matched. So also the @ which isn't desired.

    0 讨论(0)
提交回复
热议问题