Laravel Routing Part 1
In this post we will learn different methods to create routes. So lets proceed.
Where to add routes?
There is a directory named routes
in every laravel project where will find web.php
file. We can write all our routes here. Use api.php
if you need to create api routes.
Basic Routing
The basic routing code looks like this.
Route::get('hello', function () {
return 'Hello Isop';
});
we can use any HTTP methods to create the routes. We just replace get
with any other method.
Routes with Parameters
We can pass parameters to our routes like this.
Route::get('taks/{id}', function ($id) {
return 'Task '.$id;
});
We also can create route which accepts optional parameters by adding ?
to parameter
Route::get('taks/{id?}', function ($id = null) {
return $id;
});
Named Routes
We can create named routes which can be used to generate url more conveniently by chaining name
function and passing string:name as parameter.
Route::get('tasks', function () {
//
})->name('tasks');
Using named routes we will be able to generate url like this.
$url = route('tasks');
I will write about other routing techniques in part 2.