Laravel is an open source PHP framework created by Taylor Otwell. It is popular for creating web applications. Laravel has an elegant syntax and it very well documented. I started experimenting with Laravel since last year and it's been a great journey so far.
A route is the initial point of entry to your application.
Your application is accessible on the web via routes or call them URIs. They are defined in the routes/web.php
file in your Laravel application. The routing feature is provided by a facade.
use Illuminate\Support\Facades\Route;
In its simplest form, a route accepts a URI and a closure (i.e an anonymous function).
Route::get('/greeting', function () {
return 'Namaste, world';
});
Route::get('/', function () {
return view('greeting', ['name' => 'Angad']);
});
Route::get('/about', function () {
return response()->json([
'name' => 'Angad',
'level' => 'Warrior',
]);
});
You can return a string, a view or other HTTP responses.
You can register a URI to respond to a specific HTTP verb or respond to multiple HTTP verbs using the match()
method.
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Route::match(['get', 'post'], '/', function () {
//
});
If a URI should respond to any HTTP verb then you can do so using by using the any()
method.
Route::any('/', function () {
//
});
Route parameters let you capture values from the URL. A parameter is specified by putting string within curly braces {name}
in the URL. It can then be accessed by the controller.
Route::get('/blog/{id}', [PostController::class, 'show']);
Then in the specified method in the controller you write the actions that are needed for this value. In the example above, this would be done in the show
method of the PostController
controller.
public function show($id) {
// do something with $id
return $id;
}
This post is a work in progress. I will keep updating it with bits and pieces of useful information regarding Laravel routing for my own reference.