Routing in Laravel 9 explained with examples
LaravelRouting is an essential part of any web application as it is the process of mapping URLs to specific actions or resources. In Laravel, routing is handled by the Illuminate Router class.
Here at Fixwebnode, we shall look into how to use Laravel's routing system to create and manage routes for your application.
Table of contents [Show]
1. Setting up the Routes
The first step in setting up routing in Laravel is to create the routes. Laravel provides several ways to do this: you can use the router’s route method to define a single route, or you can use the router’s group method to define a group of routes.
For example, if you want to create a route for displaying a list of users, you can use the route method like this:
Route::get('/users', 'UserController@index');
This will create a GET request route that calls the index method of the UserController class when accessed.
If you want to create multiple routes related to users, like displaying a single user, creating a user, and deleting a user, you can use the group method like this:
Route::group(['prefix' => 'users'], function () {
Route::get('/', 'UserController@index');
Route::get('/{user}', 'UserController@show');
Route::post('/', 'UserController@create');
Route::delete('/{user}', 'UserController@delete');
});
The group method allows you to define a prefix for all of the routes in the group, so the above example will create the following routes:
GET /users
GET /users/{user}
POST /users
DELETE /users/{user}
2. Working with Controllers
In the examples above, the route methods refer to methods in a controller class. Controller classes are used to group related logic and are a great way to keep your application’s code organized.
For example, the UserController class might look like this:
class UserController
{
public function index()
{
// code to display a list of users
}
public function show($user)
{
// code to display a single user
}
public function create()
{
// code to create a new user
}
public function delete($user)
{
// code to delete a user
}
}
3. Working with Middleware
Middleware is a great way to add extra functionality to your routes. For example, if you want to make sure that a user is logged in before they can view a list of users, you can use the auth middleware like this:
Route::get('/users', 'UserController@index')->middleware('auth');
This will make sure that only logged in users can access the route.
4. Working with Named Routes
Named routes are a great way to make sure your routes are easy to reference in your code. For example, if you have a route to display a single user, you can give it a name like this:
Route::get('/users/{user}', 'UserController@show')->name('users.show');
Now, whenever you need to reference this route in your code, you can do it like this:
$url = route('users.show', ['user' => $user]);
[Need Laravel Application issues fix ? We can help you. ]