Skip to content

Instantly share code, notes, and snippets.

@brandonferens
Created August 20, 2014 20:23
Show Gist options
  • Save brandonferens/877bde0948f4e52550e9 to your computer and use it in GitHub Desktop.
Save brandonferens/877bde0948f4e52550e9 to your computer and use it in GitHub Desktop.
Load relative javascript assets based on route in Laravel
function loadRelativeAssets()
{
$routeArray = explode('.', Route::currentRouteName());
// We take the current route, create an array form it, run it
// through the while statement checking to see if that file exists.
// If it does, we load it. Then we remove that last element
// from the array, and do it all again, until the array is empty
while (!empty($routeArray)) {
// Create the path to the js file
$path = 'js/' . implode('/', $routeArray) . '.js';
// Create the asset name
$name = implode('', $routeArray);
// Check to see if the file exists within /public/js
if (File::exists(public_path() . '/' . $path)) {
// If the file exists, load it into Theme::asset()
Theme::asset()->container('footer')->add($name, $path);
}
// Remove the last element from the array
array_pop($routeArray);
}
}
loadRelativeAssets();
@nateritter
Copy link

Brilliant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment