Laravel Routes
Routing is a fundamental part of any Laravel project. Routes take the URL provided by the user and determine which view or controller method to invoke.
Route File
For most applications, routes will be defined in the routes/web.php
file. Routes defined here may be accessed by entering the defined route's URL in the browser. For example, for a standard installation of the Laravel, the following route will be defined in routes/web.php
.
// routes/web.php
Route::get('/', function () {
return view('welcome');
});
This route defines what should be displayed when the user visits the website's root or home page. In this case, it will load the 'welcome' view file. We will discuss the view in more detail later on. For now, let break down the route definition.
Route Definition
All routes start with call to the Route
class, which is immediately following by a static method. While in most cases, this method will be get
, the Route
has several available methods, which respond to a specific HTTP request method. The available methods are as follows:
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Each Route
method takes to arguments, a URI, the path which will be entered in the browser, and a function. The return value of the function will be what will be displayed on the page. This return value could be a simple string, as shown in the following example, or it could point to a view file, which will be discussed in more detail in the next section.
Route::get('/welcome', function () {
return 'Hello World';
});
Route Parameters
Route Parameters allow you to capture segments of the route URI. Route parameters can be either required or optional and are always encased with braces {}
. The value of the route parameter is passed to the routes callback function or the controller's method.
// required route parameter
Route::get('/user/{id}', function ($id) {
return "User {$id}";
});
// optional route parameter
Route::get('/user/{name?}', function ($name = 'Guest') {
return "Hello, {$name}";
});