This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
In laravel, I needed to dynamically get the name of the current controller for use in the view. I ended up with this solution that I'm not completely happy with. Can anybody recommend any way to clean this code up?
In app/helpers/ViewHelper.php
<?php namespace helpers;
use Illuminate\Routing\Router;
use Illuminate\Support\Str;
class ViewHelper {
protected $route;
function __construct(Router $route) {
$this->route = $route;
}
function current_controller_name() {
//This returns a string like 'UsersController@edit'
$route = $this->route->getCurrentRoute()->getOptions()['_uses'];
// The sub-string before 'Controller'
$controller = substr($route,0,strpos($route, 'Controller'));
$controller = strtolower($controller);
return Str::plural($controller);
}
}
And in the view:
<?php $controller_name = (new ViewHelper($app['router']))->current_controller_name() ?>
<link rel='stylesheet' href="/assets/<?=$controller_name?>.js") />
The call you have to make in the view feels a bit tedious. Maybe there's another package I can use instead to accomplish the same thing?
I was thinking it might be better to extend the Router class directly, although I'm not sure what that might look like.(or if its a good idea)
Subreddit
Post Details
- Posted
- 11 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/laravel/com...