Dynamically link assets

Submitted by JonathanFrias - 5 years ago

A Link assets based on which controller is currently requested. Any improvements to this code are welcome

Helper Code

<?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 of route the before the Controller
    $controller = substr($route,0,strpos($route, 'Controller'));
    $controller = strtolower($controller);
    return Str::plural($controller);

Inside the View:

<?php $controller_name = (new ViewHelper($app['router']))->current_controller_name() ?>
<link rel='stylesheet' href="/assets/<?=$controller_name?>.js") />
<link rel='stylesheet' href="/assets/<?=$controller_name?>.css") />

comments powered by Disqus