Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Laravel 5 controller name in view

Tags:

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 switching to Laravel 5. I found a way to get the action name through the Route class, but can't find a method for the controller name. I don't see anything in the Laravel docs like this. Any ideas?

This is how you do with action. You inject the Route class, and then call:

$route->getActionName().

I'm looking for something similar for controllers. I've checked the entire route class and found nothing.

like image 309
sehummel Avatar asked Apr 09 '15 21:04

sehummel


1 Answers

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.

like image 181
Martin Bean Avatar answered Sep 21 '22 09:09

Martin Bean