Laravel Routing Part 2
We are here in second part of the laravel routing. So lets proceed.
Controller Routes
We can also create controller routs that takes controller method name as closure. The syntax looks something like this.
Route::get('tasks', 'TaskController@index');
Grouped Routes/ Route Groups
Routes can be grouped using many options such as middleware, namespace , subdomain or prefix.
Route grouped with prefix look like this.
Route::prefix('tasks')->group(function () {
Route::get('/', function () {
// Matches The "/tasks" URL
}); Route::get('/create', function () {
// Matches The "/tasks/create" URL
});
...
});
We can also group routes by namespace. Lets say we want to crate routes for the controller that is in App\Http\Controllers\Admin. We can group routes like this.
Route::namespace('Admin')->group(function () {
// Controllers Within The "App\Http\Controllers\Admin" Namespace
});
You can check more options in the official laravel docs here.
Route Model Binding
When we pass model id we have to first write code to retrieve the data for the model id. With route model binding the model instance gets automatically injected directly in the route. Lets look at an example to understand this.
Lets say we have created a route to show the details of a task. The code to get the data for the specific task will look like this without route model binding.
Route::get('tasks/{taskId}', function ($taskId) { // code to get the details of task related to the id you passed
$task = Task::find($taskId);
dd($taks);
});
The same route with route model binding will look like this.
Route::get('tasks/{task}', function (Task $task) {
dd($task);
});
Here in the second example you donot need to write code to retrieve the data manually. It is done automatically for you.
There are many more techniques to create routes such as resource routes, nested routes. We will look into those in their corresponding posts.
Also you can find all about routing here.