DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

L is for Laravel; Routes

Excerpts from the book Laravel Up and Running by Matt Stauffer

Route naming convention

resourcePlural.action

Eg.
photos.index
photos.create
photos.edit

Route groups

Route groups allow grouping several routes together, and apply shared configuration settings

Defining a route group

Route::group([],function(){
Route::get('hello',function){
return 'hello';
});
Route::get('world',function(){
return 'world';
});
});

Though there is no difference in separating the routes in above group, the square brackets passed as first parameter allows to pass in various configuration that can be applied to the entire route group!

Note: The function passed in as second parameter above is called closure; Laravel's implementation of anonymous function.

Another use of Route Group is the use of Middlewares.
Ex. Restricting a group of routes to logged-in users only

Route::group(['middleware'=>'auth'],function(){
Route::get('dashboard',function(){
return view('dashboard');
});
Route::get('account',function(){
return view('account');
});
});

What above code does is users need to be logged in to the application to view the dashboard or the account page.

Instead of attaching middlewares to the routes definition,it is better to attach directly to the controllers.

String that is passed in the middleware() method is the middleware, which can me chained with modifier methods only() and except() to define which method will receive the middleware

Eg.
class DashboardController extends Controller
{
public function __construct() //constructor method
{
$this->middleware('auth');
$this->middleware('admin-auth')->only('admin'); //or ->except('admin');
}
}

Path Prefixes
Route groups can also be used to simplify path prefixes.
Eg. if the site's api is prefixed with /api:
Route::group(['prefix'=>'api'],function(){
Route::get('/',function(){
//Handles the path /api
});
Route::get('users',function(){
//Handles the path /api/users
});
});

Note: /api represents the root of the prefixed group in above example

Top comments (0)