Setting up middleware group in Laravel

If you are adding some same middleware in almost all routes defined in Laravel, then you should create a middleware group. By creating a group you can implement multiples middleware just by putting only group name in route.

Here are some main advantages of creating middleware group in Laravel-

  1. It helps to generalize the code.
  2. You save time from writing multiple middleware names in multiple places.
  3. If you need to add a middleware in all routes, don’t worry you can just add in middleware group.
  4. Reduces the complexity.

Now, let’s talk about how to create middleware groups

In the file app/Http/Kernel.php you will see a protected class variable “$middlewareGroups” which stores an empty array, you just need to add namespaces of middleware and name of the group like-

 

Here, I have created 3 middleware groups – “web” and “api” and “both” which is a combination of first 2 groups.

Now, let’s see how we can use these middleware groups in routes/api.php

As you can see, middleware group can be used same as a single middleware in route files.

Note: Code samples are from Laravel 5.5.

Read how to insert multiple entries trhough a single in eloquent.

Please follow and like us:
20

Leave a Reply