Routing in Laravel

In this post we will learn route definitions in Laravel.

Route definitions are written in the routes directory in Laravel.

Http routes are defined in the web.php file

The simplest route definition is


Route::get('/', function () {
return "Default";
});

This will be accessed via the url.

http://localhost/laraveltest/public/

Here is another route


Route::get('/one', function () {
return 'one';
});

Will be accessed by

http://localhost/laraveltest/public/one

Next, we have a path with a parameter


Route::get('two/{id}', function ($id) {
return 'two '.$id;
});

http://localhost/laraveltest/public/two/19

 

Optional parameters will require parameters with default values.


Route::get('three/{id?}', function ($id=0) {
return 'three '.$id;
});

Access with   http://localhost/laraveltest/public/three/34

 

If the default parameter is not given http://localhost/laraveltest/public/three

Route with multiple parameters

http://localhost/laraveltest/public/multiple/2/next/4


Route::get('multiple/{id1}/next/{id2}', function ($id1, $id2) {
return 'Multiple one '.$id1 . "two ". $id2;
});

 

Another multiple parameter route

http://localhost/laraveltest/public/date/2020/5/7


 

Route::get('date/{year?}/{month?}/{day?}', function ($year=2019,$month=2, $day=4) {
return 'Year= '.$year . ", Month= ". $month . ", Day = " . $day ;
});

http://localhost/laraveltest/public/date/2020


Route::get('date/{year?}/{month?}/{day?}', function ($year=2019,$month=2, $day=4) {
return 'Year= '.$year . ", Month= ". $month . ", Day = " . $day ;
});

 

Next post will deal with regular expressions


 

Route::get('/{search?}', function ($search=0) {
return "search";
})->where('Unmatched', '.*');

 

 

 

 

 

Leave a Reply