Introduction
The routing system within Laravel is one of its core features, enabling the mapping between a URL path within a users search bar to an action (controllers, views, closures) within the application.
Basic Routes
We define routes in the routes/ directory and their file names will be either the routes/web.php file or. routes/api.php file.
web.php ← used for web routes (session state, CSRF protection, etc)
api.php ← used for stateless API routes (calls), returning (generally) JSON responses.
Syntax below
Route::get(); // the routing function
// we enter the name and function as the 2 parameters to the routing function
Route::get(‘/home’, function(){ return ‘Hello, World’ });
So if the user enters /home within the search bar it will return the above string ‘Hello, World’. We will show how to enter Controllers, other as the second parameter within the routing function later in the article.
Common HTTP Methods
To be more precise, the routing function itself can be seen as an HTTP method which we access through the route class that is provided by the Laravel framework.
Route::get(): For retrieving data from a resource (think:get user from db.users)
Route::post():: For submitting data into a resource (think: insert user into db.users)
Route::put(): For submitting data (e.g,. forms)
Route::patch(): Same as put()
Route::delete(): For deleting resources (think:removing user from db.users, other)
Route::any(): Matches all methods
Route::match([‘get’, ‘post’], ‘/path’, …: Matches specified methods.
Named Routes
The giving of name(s) to particular route(s) is possible by accessing the name method/function from the routing method we are defining and giving it a string parameter with the name you are giving it. Example below
…get(‘/user/profile’, function () { … })→name(‘profile’):
greater detail
Route::get(‘/user/profile’, function () { return ‘User Profile’’ })→name(‘profile’);
generating the URL
$url = route(‘profile’);
Example of a user accessing the url
We can view the use of name function as giving the function within the routing function a name, by default it is an anonymous function.
…., function() {}); ← this is anonymous function within the get() method we defined above.
…, () => {}); ← this is the es6 arrow function
Route Parameters
We've touched on the parameters given to the routing function previously but here's something new:
Route::get(‘/user/{id}’, () => {}) ← given new variable value
{id} ← this value can be any variable type (string | null | other)
We can use this to retrieve specific items from a resource, like a particular user with id of 2.
Route::get(‘/user/{2});
We can also give the request an optional parameter
Route::get(‘/post/{id?}…
Route Groups
This is used when we have multiple route actions which share common attributes
(e.g., middleware, namespace, prefix).
Example with Prefix:
Route::prefix(‘admin’)→group(function() {
Route::get(‘/dashboard’, function () { return ‘Admin Dashboard’;});
Route::get(‘/users/’, function (){ return ‘Admin Users’; });}
Example using Middleware:
Route::middleware([‘auth’])→group(function() {
Route::get(‘/dashboard’, function () { return ‘Authenticated Dashboard’; });
});
Route Namespacing
Defining a namespace for grouped routes to use specific controllers easily.
Route::namespace(‘Admin’)→group(function () {
Route::get(‘/dashboard’, ‘DashboardController@index’);
});
Route Controllers
Route logic can be assigned to a controller instead of a closure.
Route::get(‘/users’, [UserController::class, ‘index’]);
Route::post(‘/users’, [UserController::class, ‘store’]);
Route Middleware
Attach middleware to routes to handle authentication (e.g., pre-processing)
Route::get(‘/dashboard’, ()=>{return ‘Dashboard’;})→middleware(‘auth’);
Route Namespacing
Define a namespace for grouped routes to use specific controllers easily
Route::namespace(‘Admin’)→group(()=>Route::get(‘/dashboard’, [DashboardController@index]);
});
Route Model Binding
Auto injection of a model’s instance based on route parameters
Route::get(‘/user/{user}’, function (User $user) { return $user→name; });
Implicit Binding
Route::get(‘/profile/{user}’, function (User $user) { return $user→name; });
Explicit Binding
Route::get(‘/profile/{user}’, [ProfileController::class, ‘show’]);
Redirects and Views
Redirects:
Route::redirect(‘/old-url’, ‘/new-url’, 301);
Directly Render Views:
Route::view(‘/welcome’, ‘welcome’, [‘name’=> ‘John’]);
Fallback Routes
Handle unmatched routes with a fallback.
Route::fallback(function() {
return ‘Page Not Found’;
});