In this tutorial you will learn about the Laravel Routing and its application with practical example.
What is Laravel routing?
Routing is one of the core components of Laravel framework, 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 app/Http/routes.php file, which is automatically loaded by the framework.
Basic Routing
A very basic Laravel routes is simply expressed as following-
1 2 3 |
Route::get('/', function () { return 'Welcome to Laravel Site.'; }); |
It accept two parameters URL and Closure (Closure is basically a anonymous function can be passed as a parameter to other functions).
These are the simplest routes defined as they really don’t require you pass to anything other than corresponding view. You need not to login or pass any parameters in their route definition.
Basic routing mostly used to display static pages in our site. Suppose you have some static pages as Home, About Us, Services and a Contact page in your site, and you want them to be routed as following –
Home page:
http://localhost:8000/
About Us page:
http://localhost:8000/about
Services page:
http://localhost:8000/services
Contact page:
http://localhost:8000/contact
All our static pages (Home, About Us, Services and Contact) will be routed as following in our app/Http/routes.php file.
1 2 3 4 5 6 7 8 9 10 11 12 |
Route::get('/', function (){ echo "<h2>This is Home Page</h2>; }); Route::get('/about', function (){ echo "<h2> This is About Us Page</h2>"; }); Route::get('/services', function (){ echo "<h2> This is Services Page</h2>"; }); Route::get('/contact', function (){ echo "<h2> This is Contact Page</h2>"; }); |
Route Parameters
Sometime you may want to pass some parameters along with the URL, it can be either required or optional to pass parameters. There are two ways to pass the parameters along with the URL –
Required Parameters
As per this route definition, it is mandatory to pass the specified parameters in the URL. For example, if you want ID must be passed within the URL to perform some action based on that ID. Route definition for this will be as following –
1 2 3 |
Route::get('student/{id}', function ($id) { return 'Student ID:'.$id; }); |
Optional Parameters
As per this route definition, it is optional to pass the specified parameters in the URL. Optional parameters can be indicated by placing a ? mark after the parameter name, make sure to set default value for the corresponding parameter. Route definition with optional parameter will be as following –
1 2 3 |
Route::get('student_name/{name?}', function ($name = 'Mark') { return $name; }); |
As per the above route definition it is optional to pass “name“, default value for “name” is “Mark“.
Regular Expression Constraints
Sometime you may want to constrain or specify your route parameter’s value, it can be simply done using the where method. The where method simply accepts two parameters that is the name of the parameter and a regular expression to match parameter’s value.
Let’s have look on following route definitions –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// only called if name contains the alphabets (both lowercase and uppercase) Route::get(student_name/{name}', function ($name) { echo "Student name is: $name"; }) ->where('name', '[A-Za-z]+'); // only called if id is numeric Route::get(student_id/{id}', function ($id) { echo "Student Id is: $id"; }) ->where('id', '[0-9]+'); Route::get(student/{id}/{name}', function ($id, $name) { echo "Student Id: $id and Student Name: $name"; }) ->where(['id' => '[0-9]+', 'name' =>'[a-z]+']); |
Global Constraints
If you want a route parameter to be constrained by a given regular expression globally for all route definitions. It can be defined using pattern method in the boot method of your RouteServiceProvider.
For example if you want route parameter id to be numeric for all route definitions, it can done as following –
1 2 3 4 5 |
public function boot(Router $router) { $router->pattern('id', '[0-9]+'); parent::boot($router); } |
1 2 3 |
Route::get('student_id/{id}', function ($id) { // Only called if id is numeric. }); |
Named Routes
Named routes gives you a way to assign easy to remember alias/name for URLs. It can be simply using the as key while creating route definition.
1 2 3 |
Route::get('student/profile', ['as' => 'profile', function () { // }]); |
Named route definition for controller actions –
1 2 3 |
Route::get('student/profile', [ 'as' => 'profile', 'uses' => 'StudentController@showProfile' ]); |
Alternatively, you can define it using chain the name method at the end of the route definition –
1 |
Route::get('student/profile', 'StudentController@showProfile')->name('profile'); |
Accessing Named Routes
Named routes can be access in your controller, view or anywhere in application as following –
1 2 3 4 5 |
// to generate $url = route('profile'); // to redirect return redirect()->route('profile'); |
Route Groups
Route groups gives you way to group a set of routes (Routes sharing common route attributes such as namespaces or middleware) in single route definition instead of defining those attributes individually.
Assign Middleware
1 2 3 4 5 |
Route::group(['middleware' => 'auth'], function () { Route::get('student/profile', function () { // Uses Auth Middleware }); }); |
Assign Namespaces
1 2 3 4 5 |
oute::group(['namespace' => 'Admin'], function() { // Controllers in "App\Http\Controllers\Admin" Namespace }); |
Route Prefixes
Route Prefixes allows you to define prefix for each route in a group by using prefix group array attribute. Suppose you are creating a CMS where you have a admin panel, you would prefer to have admin as prefix for set of routes belongs to admin panel. Then it can defined as following –
1 2 3 4 5 |
Route::group(['prefix' => 'admin'], function () { Route::get('students', function () { // Matches The "/admin/students" URL }); }); |
Router Methods for other HTTP Requests
Route::post(‘url’, ‘closure’) :- It is used to create an Item
Route::put(‘url’, ‘closure’) :- It is used to update an Item
Route::delete(‘url’, ‘closure’) :- It is used to delete an Item
Route::match(‘[‘get’, ‘post’]’,’url’, ‘closure’) :- It is used to define a route that responds to more than one type of HTTP requests.
Route::any(‘url’, ‘closure’) :- This responds to all types of HTTP requests.