Routing is one of the essential concepts in Laravel. Routing in Laravel allows you to route all your application requests to its appropriate controller. The main functionality of the routes is to route all your application requests to the appropriate controller.
Routing in Laravel includes the following categories −
- Basic Routing
- Route parameters
- Named Routes
Basic Routing
All the routes in Laravel are defined within the routes/web.php file. This file tells Laravel for the URIs it should respond to and the associated controller will give it a particular call.
The routes/web.php directory contains the definition of route files for your web interface. The routes in web.php are assigned with the web middleware group that provides the features like session state and CSRF protection. The routes defined in routes/api.php are assigned with the API middleware group, and they are stateless.
The definition of default route files.
Route::get('/', function () { return view('welcome'); });
In the above example, Route is the class which defines the static method get(). The get() method contains the parameters ‘/’ and function() closure. The ‘/’ defines the root directory and function() defines the functionality of the get() method.
Route Parameters
Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in the routes/web.php file.
Laravel provides two ways of capturing the passed parameter:
- Required parameter
- Optional Parameter
Required Parameters
These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below −
Route::get('id/{id}',function($id) { echo 'ID: '.$id; });
Optional Parameters
Many parameters do not remain present within the URL, but the developers had to use them. So such parameters get indicated by a “?” (question mark sign) following the parameter’s name.
Route::get('user/{name?}', function ($name = 'infovistar') { return $name; });
Named Routes
Named routes allow a convenient way of creating routes. The chaining of routes can be specified using the name method onto the route definition. The following code shows an example for creating named routes with controller −
Route::get('user/profile', 'UserController@displayProfile')->name('profile');
The user controller will call for the function displayProfile with parameter as a profile. The parameters use the name method in the route definition.