In Laravel, all requests are mapped with the help of routes. it is simply a mechanism that performs the mapping for your requests to a specific controller action.
All Laravel routes are defined in the file located as routes/web.php file, which is automatically loaded by the framework.
There are several types of routes given below-
1- Basic Routes:
Basic routes are the most common type of routes in Laravel. They respond to HTTP requests like GET, POST, PUT, DELETE, etc., and map the URL to a specific controller method or closure function.
Example:
Route::get('/home', 'HomeController@index'); Route::post('/submit', 'FormController@submit'); Route::put('/update/{id}', 'UserController@update'); Route::delete('/delete/{id}', 'UserController@delete');
2- Route Parameters:
You can define route parameters to capture parts of the URL and pass them as arguments to your controller methods. Parameters are enclosed in curly braces {}
.
Example:
Route::get('/user/{id}', 'UserController@show');
3- Named Routes:
Named routes allow you to assign a unique name to a route. This makes it easier to reference the route in your application’s code. You can use the name
method to name a route.
Example:
Route::get('/profile', 'ProfileController@show')->name('profile.show');
4- Route Groups:
Route groups allow you to apply common attributes, such as middleware or a prefix, to a group of routes. This helps keep your routes organized and makes it easier to maintain the application.
Example:
Route::prefix('admin')->middleware('auth')->group(function () { // Admin routes go here... });
5- Resource Routes:
Resource routes are used for creating routes that follow RESTful conventions. They automatically generate routes for common CRUD operations (Create, Read, Update, Delete) for a resource (e.g., posts, products) in a controller.
Example:
Route::resource('posts', 'PostController');
6- API Resource Routes:
API resource routes are similar to resource routes but are typically used for building API endpoints. They generate routes for standard CRUD operations but without the need for rendering views.
Example:
Route::apiResource('products', 'ProductController');
7- Fallback Routes:
Fallback routes are used to handle requests that don’t match any of the defined routes. These routes are useful for implementing custom 404 error pages or handling unknown routes.
Example:
Route::fallback(function () { // Custom 404 error page or response });