- Laravel Basic Routing
- Laravel Routing Parameters
- Named Routes
- Route Groups
Basic Routing
Redirect Routes
View Routes
The Route List
Route Parameters
Required Parameters
Optional Parameters
Regular Expression Constraints
Named Routes
Route Groups
Middleware
Controllers
Subdomain Routing
Route Prefixes
Route Name Prefixes
Route Model Binding
Implicit Binding
Implicit Enum Binding
Explicit Binding
Fallback Routes
Rate Limiting
Defining Rate Limiters
Attaching Rate Limiters To Routes
Form Method Spoofing
Accessing The Current Route
Cross-Origin Resource Sharing (CORS)
Route Caching
Laravel Basic Routing
Routing is one of the essential concepts in Laravel. The main functionality of the routes is to route all your application requests to the appropriate controller.
Default Route files
All Laravel routes are defined inside the route files located in the routes directory.These files are automatically loaded by your application's App\Providers\RouteServiceProvider. When we create a project, then a route directory is created inside the project. The route/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.
We will start by defining the routes in routes/web.api file. The routes defined in the routes/web.php can be accessed by entering the defined URL to the browser. Let's understand this through an example.
The definition of default route files.
<?php
Route::get('/', function ()
{
return view ('welcome');
});
In the above case, 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.
In the above route, the url is '/';
therefore, we entered the localhost/laravelproject/public URL in the web browser.
Laravel Basic Routing
As the method returns the view('welcome'), so the above output shows the welcome view of the Laravel.
Let's see another example.
Now, we provide another url in this example.
<?php
Route::get('/example', function ()
{
return "Hello javaTpoint";
});
In the above example, the route is defined in which URL is '/example',
so we need to enter the URL "localhost/laravelproject/public/example"
in the web browser.
Output:
** Laravel Basic**
CSRF Protection
The HTML forms that are pointing to Post, Put or Delete routes defined in the web route files should include CSRF token field. If the CSRF token field is not included, then the request will be rejected.
<form method="POST" action="/profile">
@csrf
...
</form>
The router defines the routes that can respond to the following http verbs:
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Sometimes the situation arises when you need to register a route that responds to the multiple http verbs, and this can be achieved by using the match() method. Sometimes you want to register a node that responds to all the http verbs, so we use any() method.
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function ()
{
//
})
Two most commonly used route methods are:
Redirect() method
Redirect() method is used to navigate from one URL to another URL. This method provides a convenient or shortcut way to move from one URI to another URI. With the help of this method, you don't need to define the full route.
There are two ways of using redirect() method:
First way is to declare the redirect() method in get() method:
<?php
Route::get('hello', function () {
return redirect('/');
})
Second way is to access the redirect() method directly.
<?php
Route::redirect('hello','/');
In the above cases, both the routes are navigating from /hello to the root directory, i.e., '/'.
View() method
View() method is used to return the view of another URL.
<?php
Route::get('/', function () {
return view('welcome');
});
<?php
Route::view('/','welcome');
The Route List
The route:list Artisan command can easily provide an overview of all of the routes that are defined by your application:
php artisan route:list
By default, the route middleware that are assigned to each route will not be displayed in the route:list output; however, you can instruct Laravel to display the route middleware by adding the -v option to the command:
php artisan route:list -v
You may also instruct Laravel to only show routes that begin with a given URI:
php artisan route:list --path=api
In addition, you may instruct Laravel to hide any routes that are defined by third-party packages by providing the --except-vendor option when executing the route:list command:
php artisan route:list --except-vendor
Likewise, you may also instruct Laravel to only show routes that are defined by third-party packages by providing the --only-vendor option when executing the route:list command:
php artisan route:list --only-vendor
Laravel Routing Parameters
There are two types of parameters we can use:
Required Parameters
Optional Parameters
Laravel Routing Parameters
Required Parameters
The required parameters are the parameters that we pass in the URL. Sometimes you want to capture some segments of the URI then this can be done by passing the parameters to the URL. For example, you want to capture the user id from the URL.
Let's see the example without route parameters.
<?php
Route::get('/', function()
{
return "This is a home page";
}
);
Route::get('/about', function()
{
return "This is a about us page";
}
);
Route::get('/contact', function()
{
return "This is a contact us page";
}
);
Output
When we enter the URL "localhost/laravelproject/public/".
Laravel Routing Parameters
When we enter the URL "localhost/laravelproject/public/about".
Laravel Routing Parameters
When we enter the URL "localhost/laravelproject/public/contact".
Laravel Routing Parameters
Let's see the example with route parameters.
Route::get('/post/{id}', function($id)
{
return "id number is : ". $id;
}
);
The route parameters are enclosed within {} brackets, and parameters must contain alphabetic characters. It should not contain '-' character, and instead of using this character, you can use '_' character.
Route parameters are available in the route callbacks. Syntax of route parameters is given below:
Name of the callback/controller arguments
Where controller arguments are the route parameters.
Laravel Routing Parameters
Let's see the example with multiple route parameters.
//We can also pass the multiple parameters.
Route::get('/post/{id}/{name}', function($id,$name)
{
return "id number is : ". $id ." ".$name;
}
);
Output
Laravel Routing Parameters
Optional Parameters
Suppose you want to specify the route parameter occasionally, in order to achieve this, you can make the route parameter optional. To make the route parameter optional, you can place '?' operator after the parameter name. If you want to provide the optional parameter, and then make sure that you have also provided the default value to the variable.
Let's understand through some examples.
Example 1:
Route::get('user/{name?}', function ($name=null) {
return $name;
});
When we do not pass any variable to the URL, then the output would be:
Laravel Routing Parameters
When we pass 'akshita' in the URL, then the output would be:
Laravel Routing Parameters
From the above outputs, we observe that the parameter we pass in the URL is optional. As we have provided the default value to the parameter as Null, so if we do not pass any parameter, it will return null. If we pass the parameter in the URL, then the value of the parameter would be displayed.
Example 2:
Route::get('user/{name?}', function ($name = 'himani') {
return $name;
});
In the above example, we have provided the default value as 'himani'.
Laravel Routing Parameters
In the above example, we do not pass any parameter, so the default value is returned.
Laravel Routing Parameters
Regular Expression Constraints
These are the constraints that can format the route parameters by using the where method on a route instance. The 'where' method accepts the name of the parameter and regular expression constraint that defines how the parameter should be constrained.
Route::get('/user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
Let's understand through some examples.
Example 1:
Suppose we want to pass the user name as a route parameter that contains only alphabetical characters.
Route::get('user/{name?}', function ($name=null) {
return $name;
})->where('name','[a-zA-Z]+');
Laravel Routing Parameters
Example 2:
Let's consider an example that accepts only numeric values.
Route::get('user/{id?}', function ($id=null) {
return "id is : ". $id;
}->where('id','[0-9]+');
Laravel Routing Parameters
Laravel Routing Parameters
Example 3:
Let's consider an example that accepts alphanumeric characters.
Route::get('user/{id}/{name}', function ($id,$name) {
return "id is : ". $id ." ,". "Name is : ".$name ;
})->where(['id'=>'[0-9]+', 'name'=>'[a-zA-Z]+']);
Laravel Routing Parameters
Global Constraints
You always want a route parameter to be constrained by a regular expression; then you can use the pattern method. You can define these patterns in the boot method of your RouteServiceProvider.
Global Constraints are used when we have multiple routes, and the same constraints are applied to all the routes. In Global Constraints, we do not have to apply the constraints individually to each route using where clause, we just need to define the pattern inside the boot() method, and it will be applied to all the routes.
Let's understand this through an example.
**Step 1: Add the pattern in the boot method of **RouteServiceProvider.php file.
public function boot()
{
Route::pattern('id', '[0-9]+');
parent::boot();
}
Step 2: Add the routes in web.php file.
Route::get('user/{id}', function ($id) {
return $id;
});
Route::get('post/{id}', function ($id) {
return $id;
});
When we pass the route parameter to the '/user' URL, then the output would be:
Laravel Routing Parameters
When we pass the route parameter to the '/post' URL, then the output would be:
Named Routes
Named routes is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.
Syntax of defining naming routes:
We can define the named routes by chaining the name method onto the route definition:
Route::get('student/details', function()
{
//
}) -> name('student_details');
We can also specify the named routes for controller actions:
Route::get('student/details', 'studentcontroller@showdetails') -> name('student_details');
Generating URLs to named routes
Once you assigned a named route to a given route, then you can use the name of the route while generating URLs or redirecting through a global route function.
*Generating URLs *
$url= route('student_details');
*Generating Redirects... *
return redirect() -> route('student_details');
Suppose we have many parameters in the URL; in this case we can provide the short name to the URL. We use an array which wraps everything, and it appears as a second parameter in a get() function. Let's understand through an example.
Route::get('student/details/example',array
('as'=>'student.details',function()
{
$url=route('student.details');
return "The url is : " .$url;
}));
Laravel Named Routes
We can also check the name of the route from the Git bash window.
First, open the Git Bash Window.
Move to the project folder on the Git Bash window, and type the command php artisan route:list.
Laravel Named Routes
The above output screen shows the URL and its corresponding name, i.e., the name of the URL "student/details/example" is student.details.
Note: The benefit of using named routes is that if we change the location of the route, then also the link will work or we can say that it is beneficial for changing the URLs dynamically.
Parameters in Named routes
Named routes can also be used to define the parameters. The parameters can be passed as the second argument to the route function, and these parameters are automatically inserted into the correct position of the URL:
Route::get('user/{id}/profile',function($id)
{
$url=route('profile',['id'=>100]);
return $url;
})->name('profile');
Output:
Laravel Named Routes
Navigating from one route to another using named routes
We can also navigate from one route to another route by using named routes.
Step 1: Define the route in the web.php file.
Route::Get('/',function()
{
return view('student');
});
Route::get('student/details',function()
{
$url=route('student.details');
return $url;
})->name('student.details');
Step 2: Move to the resources folder and then click on the views folder.
Step 3: Create a new file and it is named as student.blade.php.
Student
The above code navigates from student page to the student.details which is the named route.
Laravel Named Routes
Laravel Named Routes
Route Groups
Route Groups is an essential feature in Laravel, which allows you to group all the routes. Routes Groups are beneficial when you want to apply the attributes to all the routes. If you use route groups, you do not have to apply the attributes individually to each route; this avoids duplication. It allows you to share the attributes such as middleware or namespaces, without defining these attributes on each individual route. These shared attributes can be passed in an array format as the first parameter to the Route::group method.
Syntax of Route Group
Route::group( [ ] , callback);
Parameters
[ ]: It is an array passed to the group method as a first parameter.
Example of Route Groups
web.php
Route::group([], function()
{
Route::get('/first',function()
{
echo "first route";
});
Route::get('/second',function()
{
echo "second route";
});
Route::get('/third',function()
{
echo "third route";
});
});
In the above code, we define the group() method, which contains the two parameters, i.e., array and closure. Inside the closure, we can define the routes as many as we want. In the above code, we define three routes.
Output:
Laravel Route Groups
Path Prefixes
Path prefixes are used when we want to provide a common URL structure.
We can specify the prefix for all the routes defined within the group by using the prefix array option in the route group.
Let's understand through an example.
web.php
Route::group(['prefix' => 'tutorial'], function()
{
Route::get('/aws',function()
{
echo "aws tutorial";
});
Route::get('/jira',function()
{
echo "jira tutorial";
});
Route::get('/testng',function()
{
echo "testng tutorial";
});
});
The above code contains three routes which can be accessed by the following URLs:
Top comments (0)