Table of Contents
-
Creating Routes in Laravel
-
Understanding the Routing Mechanism
-
Using Route Parameters
-
Required Parameters
-
Optional Parameters
-
1. Creating Routes in Laravel
In Laravel, all routes are defined within the routes
directory. These route files are automatically loaded by the framework. The main route file is routes/web.php
for web routes and routes/api.php
for API routes.
Example Routes:
Route::get('/', function () {
return 'Welcome to the index page';
});
Route::post('user/dashboard', function () {
return 'Welcome to the dashboard';
});
Route::put('user/add', function () {
// Handle updating or adding a user
});
Route::delete('post/example', function () {
// Handle deleting a post
});
2. Understanding the Routing Mechanism
The routing mechanism in Laravel follows these three main steps:
-
The root URL of the project is created and accessed.
-
The URL matches a predefined method in the
routes/web.php
file, triggering the corresponding function. -
The function processes the request and may call a view template to generate a response.
Example:
Route::get('/', function () {
return view('laravel');
});
Corresponding view file:
resources/views/laravel.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Tutorial</title>
</head>
<body>
<h2>Laravel Tutorial</h2>
<p>Welcome to the Laravel tutorial.</p>
</body>
</html>
3. Using Route Parameters
Sometimes, applications need to capture parameters passed through the URL. Laravel provides two types of route parameters:
Required Parameters
A required parameter must always be provided in the URL. It is enclosed in {}
within the route definition.
Example:
Route::get('employee/{id}', function ($id) {
return 'Employee ID: ' . $id;
});
Optional Parameters
Optional parameters are not always required in the URL and are indicated by a ?
after the parameter name. You can also provide a default value.
Example:
Route::get('employee/{designation?}', function ($designation = 'Not Specified') {
return 'Designation: ' . $designation;
});
Route::get('employee/{name?}', function ($name = 'Guest') {
return 'Hello, ' . $name;
});