Learn about routing in Laravel

Tram Ho

Hello, when starting to learn about Laravel, you cannot ignore some basic concepts such as Routing, Middleware, Controllers, Model, Requests, Responses, Views .

In this article I will introduce some basic concepts about Routing.

The purpose and function of routing in Laravel is to route a user’s requests to a specific function, or a piece of logic that handles the user’s request.

The default location of route files

All route files in the Laravel project are located in the routes / directory. The default Laravel project installation has the following files: – routes / web.php: Defining routes for your web interface – routes / api.php: Defining routes for api

Methods in a Route

Routes that support methods of communication between the browser and the server via HTTP:

In addition, laravel also supports us to define routes that handle multiple methods with the same response returned as match and any :

CSRF Protection

Every time we use any form that points to routes that support POST, PUT or DELETE we must attach a csrf protection in the request, otherwise the request will be rejected.

Route Parameters

Sometimes we need to use the URI to send the required parameters, stay in laravel to get that parameter we can define as follows:

We can define multiple parameters on a route as follows:

Route parameters are always defined in braces {} , and must not contain special characters.

In addition we can define optional parameters for parameters, we just need to declare more ? after the name of the parameter eg:

Constrain regular expressions

We can restrict the format of the input parameters with a regular expression, Laravel has supported us to do that with the where method:

Name the route

You can name a specific route and the purpose of this naming so we can access the url of the route faster:

To be clearer, let’s take a look at the following example where you can see the benefits of naming a route:

After naming them we can retrieve the url address or redirect to that route.

Above are some basic concepts about routes in Laravel, to be able to better understand some of the other concepts you can refer to.

Share the news now

Source : Viblo