Laravel web routes

Well you already understand how MVC works (however I don’t wrote about Laravel Lifecycle, uhrr… I’m planning a dedicated post about it) and you also know how artisan works but now it’s time to understand more about routes ­čśë

We have 4  types of routes:

  • api
  • channels
  • console
  • web

The routes are defined in routes/type.php, in this post we will talk about web routes.

This post is based on things that I think is important to understand, the documentation is greater than it post.

We often use the Route Facade (defined in our /config/app.php in aliases array ), lets check this file.

The Route Facade

Well, if you already stop to think where is the Route Facade, the answer is:

As you see, there are the all route methods, except the two new methods of Laravel 5.5: view and redirect.

If you don’t remember, Laravel uses the REST┬ádesign pattern.

How it works?

So think in Route as an collection and when you use some of these methods in Route Facade, it will push and register a new route in these collection like an array. Something like this:

Will result in:

And behind the scenes the framework will receives a request and will search for the correct path and verb when it matches will call the Class and method passing the correct parameters.

You also have the resource method and apiResource. You can read more HERE.

Important things about routes:

  • Can be cached – except routes with closures
  • Can be named – to make links easily
  • Can be resourcefull
  • Can be grouped

Examples

CSRF Protection – Important to know

Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected. You can read more about CSRF protection in the CSRF documentation:

Route Params

It’s true that in very much cases we need to pass parameters, and Laravel have a super cool thing called Implicit Biding.

First a simple example of required parameter and optional parameter.

Implicit binding

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name. For example:

Since the $user variable is type-hinted as the App\User Eloquent model and the variable name matches the {user} URI segment, Laravel will automatically inject the model instance that has an ID matching the corresponding value from the request URI. If a matching model instance is not found in the database, a 404 HTTP response will automatically be generated.

 

I advice you to read all documentation about routes here.

Share this!




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *

*