Routing
All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework.
The routes/web.php file defines routes that are for your web interface.
For most applications, you will begin by defining routes in your routes/web.php file.
Syntax:-
Route::get(‘URI’, Closure/Callback); | |
// Example:- | |
Route::get(‘about', function () { | |
return 'Hello World'; | |
}); |
Route Returning String
//Syntax:- | |
Route::get(‘URI’, Closure/Callback); | |
//Example:- | |
Route::get(‘about', function () { | |
return 'Hello World'; | |
}); |
Routes Parameter
Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user’s ID from the URL.
Syntax:- | |
Route::get(‘uri/{p_para}', function ($para) { | |
return $para; | |
}); | |
Example:- | |
Route::get(‘user/{u_id}', function ($id) { | |
return $id; | |
}); |
Routes Multiple Parameter
Note – Route parameters are always encased within {} braces and should consist of alphabetic characters, and may not contain a – character.
// Example:- | |
Route::get(‘post/{post_id}/comment/{comment_id}', function ($post_id, $comment_id) { | |
return $post_id . $comment_id; | |
}); |
Optional Routes Parameter
We can make optional parameter by placing a ? Mark after the parameter name.
//Example:- | |
Route::get(‘student/{name?}', function ($name = null) { | |
return $name; | |
}); | |
Route::get(‘student/{name?}', function ($name = ‘Amardeep') { | |
return $name; | |
}); |
Routes Parameter and Regular Expression
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained.
//Syntax:- | |
Route::get(‘uri/{p_para}', function ($para) { | |
return $para; | |
})->where(‘p_para’, ‘Regular Expression’); | |
//Example:- | |
Route::get(‘product/{p_name}', function ($name) { | |
return $name; | |
})->where(‘p_name', '[A-Za-z]+'); |
Routes Parameter with Regular Expression Helper Method
Route::get('user/{id}/{name}', function ($id, $name) { | |
// | |
})->whereNumber('id')->whereAlpha('name'); | |
Route::get('user/{id}', function ($id) { | |
// | |
})->whereUuid('id'); |
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND