Routing

Updated on Jul 11, 2024

Routing is a fundamental functionality in Laravel. What it does is it tells application requests where to go and to which controllers. Earlier in this tutorial, we explained that an application's logic is contained in a controller. In simpler terms, when a user requests an action from the application (like clicking on a button, for instance), the Controller takes that request and delivers it to the appropriate part of the application's code or database to elicit the correct response. It then delivers the response to the user, and the user sees what the button does. That is an oversimplification of the process, so let's dive deeper into how routing actually works.

This Tutorial Includes

section

How it Works?

Firstly, all routes are defined in the routes directory of your Laravel application. A brand new Laravel installation will have these four files.

Let's explain what each of them does in more detail.

  • api.php - All routes within this file have the API middleware group; therefore, all routes that utilize an API will be stored here;
  • channels.php - All routes that are used to broadcast data are stored here. Such "broadcasting" is done via WebSockets, and in most simple terms, these broadcasts are used to send data to a user without needing a page refresh. New messages in a chat window are the most straightforward example: chat messages appear instantly, without having to refresh the page to see them;
  • console.php - Users can create custom Artisan commands, and they are stored in this file, along with all of their logic;
  • web.php - This file contains all routes related directly to your web application's functionality. The route for the example with the button we gave earlier will be in this file.

Now, let's give an example. The following code block will display a message on our application's homepage.

<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
 return view('welcome');
});

You would not be wrong if you think this code seems familiar. It is the default code that appears in the web.php file, which in turn returns Laravel’s default homepage. Let's break it down.

Firstly, we have the Route class, which takes us to the get() method. Basically, we are asking the application to fetch something for us. We have provided two parameters within the parenthesis: '/' and function. The slash signifies the root directory of our application. When you see a slash like that, it likely means that the route will be directed to the root directory.

On the other hand, function defines the functionality of the get() method. Finally, the return view method instructs the app to return the output in the parenthesis. In this case a View named “welcome.” While this is a very basic example, it perfectly portrays a route's structure and interaction with the application. Finally, keep track of your parenthesis and brackets, and do not leave any of them without their partner; otherwise, something might break in the application.

Simply put, a route has to define the application's method to obtain the function it has to use and then what the output will be. It is a constant back-and-forth between the user and the application. Next, we will look at further customizing a route through parameters.

section

Parameters

Route parameters, or just parameters, are crucial to how Routes function. They are excellent if you want your routes to be flexible and able to handle various requests. You can think of parameters as modifiers for your routes that tell them to act slightly differently when making a specific request. In other words, they retrieve data from the database when a particular parameter is provided, as the name suggests.

Curly braces always surround parameters and can contain only letters, numbers, and underscores. 

Let's look at an example to clarify things some more. Take this route, which we will place in the routes/web.php file.

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

First, we have the route and then the {id} parameter. In this case, it is a placeholder, which we will fill out with the application URL. When we open the application in a browser and go to /user/1, the application will return the database entry for that user. As you can see, we didn't go to /user/id and instead used the route parameter to request data from the database for a specific user. That is what we meant when we said parameters make routes flexible and able to handle different requests.

You can also define multiple parameters in a route, but be careful how you place them, as their order matters. It is like the directories in a file structure: don't put the Games directory before Disk D:. The same logic applies here. 

There are two types of parameters within the Laravel application: required and optional. The one from the example above is a required parameter. You can recognize optional parameters because they will have a question mark (?) after them, like this.

Route::get('user/{name?}', function ($name=null) {
 return $name;
});

The question mark signifies an optional parameter, triggering only when a variable that fits its parameters is given. If we go to /user/name but don't give any parameter, then all we would see is the /user/name page. But if we provide a parameter to it, say /user/name/Daniel, we will see the database entry for Daniel. Optional parameters like that are very useful, as they allow you to have a route that doesn't necessarily require a parameter to function. Just ensure you have the correct database entries set up; otherwise, the application won't know what to do with these parameters.

Finally, you can filter your parameters' functionality through specific methods. That is called constraining, and we will give you an example and explain it.

Route::get('/user/{name}', function (string $name) {
	// ...
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}', function (string $id) {
         // ...
})->where('id', '[0-9]+');

We have the {name} and {id} parameters in the example. However, you will notice that there is now a where method. That method accepts the parameter's name and then defines the regular expression that can interact with it. The example shows that the name can only accept upper and lowercase letters, and the id will only accept numbers. If the parameter is requested with any other constraint outside of the defined ones, a 404 page will appear instead. If you have repeating patterns or would like to restrict a specific pattern globally, you can also do that. Simply go to the App\Providers\RouteServiceProvider file in your Laravel installation and use the pattern method. Here is a brief example.

/**
* Define your route model bindings, pattern filters, etc.
*/
public function boot(): void
{
 Route::pattern('id', '[0-9]+');
}

As you can see, the pattern is defined for the id parameter and its constraints. Once this is done, the pattern will apply to all parameters of the id type.

That concludes our look into route parameters. They are a handy bit of functionality within Laravel, allowing you to define more flexible and useful routes than usual.

On this page...