Skip to content

Instantly share code, notes, and snippets.

@jslim89
Last active November 18, 2015 04:57
Show Gist options
  • Save jslim89/0f4003ffd5c0932ae73f to your computer and use it in GitHub Desktop.
Save jslim89/0f4003ffd5c0932ae73f to your computer and use it in GitHub Desktop.
Laravel 5 helpers

Create helpers in Laravel 5

First, create a helper folder

$ mkdir app/Helpers

Then create helper files, in my case I create route helper

$ touch app/Helpers/routes_helper.php

Usage

routes_helpers

This is useful when you want to get the route by it's name

e.g. in your app/Http/routes.php

<?php
Route::get('auth/login', ['as' => 'auth.login', 'uses' => 'Auth\AuthController@getLogin']);

The as is actually the route name. With this helper you can get the route like this

$route = route_from_name('auth.login');
{
....
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/routes_helper.php"
]
},
...
}
<?php
/**
* Get Route from route name
*
* @param string $name
* @access public
* @return \Illuminate\Routing\Route
*/
if (!function_exists('route_from_name')) {
function route_from_name($name) {
$collection = Route::getRoutes();
$routes = $collection->getRoutes();
foreach ($routes as $route) {
$action = $route->getAction();
if (isset($action['as']) && $action['as'] == $name) {
return $route;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment