Laravel Basic Routing
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. A standard installation of the Laravel the following route will defined in routes/web.php
.
// routes/web.php
Route::get('/', function () {
return view('welcome');
});
What this route is doing is defining what should displayed when the user visit the web site root or home page. In this case will load the 'welcome' view file. We will discuss 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 the which will be enter 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';
});
Routes to a View
Views are a separate file that contain the HTML that will be displayed on the page. These files can be found in the resources/views
directory. Traditionally, views are Blade files (.blade.php
), which is Laravel's templating engine. We will discuss views in more details later on in this course.
Routes can be set to point directly to a view. This can be done using the view
helper function inside of the callback function. The view
helper function is used to retrieve a view instance. It takes the name of the view as its first argument and an optional second argument as the data array.
Route::get('/welcome', function () {
return view('welcome');
});
Another approach for loading a view is to use the view
method of the Route
class. The view
method accepts a URI as its first argument and a view name as its second argument. In addition, an optional third argument may be used to pass data to the view. We will discuss feature on the next page.
Route::view('/welcome', 'welcome');
Both of the examples above produce the same result.