What are Laravel Filters?

what are laravel filters

Filters are really a fantastic resource to use in Laravel. In fact, almost all applications will use them in one way or another. Filters give you the ability to tap into the routing lifecycle within Laravel and take actions based on various conditions both before and after the route request and response. We also saw in the last episode on Larvael Cache techniques, that we can combine the use of filters and caching together. There are many useful things we can do with Filters in Laravel, so let’s get right to it!

Restricting Access to a Route

Route filters are a great method to use in order to limit access to a given route. This is an important feature to have when there are areas of the website that should only be accessed by authorized users. Your web application or website likely has an admin area. One way to keep non qualified users away from that route is to use a filter. So suppose you have your top secret highly classified information in this admin area and you have a route file like this:

Right now, anyone can view this page as you can see here.

laravel auth filter

Built in Laravel Filters

Laravel Auth Filter

The auth filter comes to your rescue! Laravel ships with some filters already built in for you to make use of in your applications. The auth filter is one of them, and it will help us in this very type of application. We can update our route to the admin area to include an auth filter just like this:

In this snippet above we do a couple things. Notice that we add the before() filter to the admin route. In addition, we added a second route to the file of login. This is so we don’t throw an exception once our auth filter kicks in to redirect any non authorized users back to the login page. In a way it almost reads backwards as in, “Before I render this admin area to you, I will run the auth filter to see if I should do this or not.” Now that we updated our admin route to include an auth filter, check out what happens when we try to visit that area of the website:

laravel auth filter login

Nice! So how did this magic work? Well, like we said earlier, Laravel ships with some filters already set up for you in app/filters.php. Let’s have a look at the code that provides this functionality to us:

What this code does for you is to simply check if the user is authorized, and send them on their way if they are not. We can see that it has support for ajax as well, which is quite slick. In our routes file we had referenced the filter by the name of ‘auth’ and we can see here how to define that very filter using Route::filter(). The Redirect::guest() method has the added benefit that once the user *is* logged in, they will be sent to whatever page they had intended to visit by way of intended redirections.

Cross Site Request Forgery Attack Filer

The default Laravel installation also has a filter to deal with CSRF attacks. CSRF attacks can lead to a user unknowingly sending HTTP requests to various websites to take actions the user has no idea is happening. At it’s most benign, the user might like a facebook page without actually realizing it. At the other end of the spectrum would be transferring money out of an online account with no knowledge of it happening. So, it is important to make sure you do put the CSRF filter to use. It’s code looks like this:

The application of a csrf filter is for routes that are going to process form data and you would call it using before(). This is the reason the Laravel Form::open() method generates a security token for you. That security token is used with this filter to eliminate any possible csrf issues for the user by way of the Synchronizer Token Pattern.

Global Application Filters

At the top of the filters.php file you’ll see the following code:

These are the global filters, meaning you can set up logic inside each of these to run on every single request in the application. They will no longer be attached to specific routes or controllers. You can find some examples of how to use these in the documentation or on sites like Laravel Recipes, Laravel Tricks, and so on.

Stacking Filters in Laravel

You can stack filters if you like, meaning you can combine multiple filters in one swoop. First off, let’s look at a different way to write the same filter we first started with. It seems that folks are apply their filters by using an array in the route as the second argument. The official docs also show it this way, so we really should take a look:

Cool. So this approach works just the same, it’s just a different syntax. Now that we know how to use this syntax, we can also make use of stacking filters. Now we are going to create the most non sensical filters you have ever seen here. They will be useful for pretty much nothing, other than showing us how the filters trigger and stack! I gave you fair warning, do not put this into your code, but do feel free to test it out for fun to see how filters get triggered!

Defining Your Own Custom Filters

Three New Filters

In our app/filters.php we can add this code:

As you can see, these filters are not doing anything useful, but I promise they will help us in understanding how we can attach them to routes! Now check out how we stack these in our routes.php by separating filter names with a pipe.

Now here is the deal partner. We no longer are using the auth filter, and we are instead going to call these three filters in succession before the admin route. Now anyone will be able to enter our administrative kingdom, and they’ll see some messages to confirm that filters were firing along the way as well. Visit the admin route, and check it:

laravel stacking filters

Oh yeah! BabaBooey! You see, we have made it to the admin area, and you can see that our filters did trigger successfully.

Passing Parameters to Filters

We’re going to kill two birds with one stone right about now. First, let’s look at some updated code in our routes file. We’re going to change how we’re applying our filters. Two things to note are the fact that we are now using method chaining, and we also changed one:booey to one:potato:

Bird 1.

You see, it’s bugging me that we went and changed up our syntax for how we apply the filter from chaining, to an array as the second argument to the route. We’re going back to chaining here as you can see. The goal is to test the pipe separation method of applying filters using the chain to see if it works via this method as well.

Bird 2.

The second bird on our radar is the fact that there is a parameter involved with filter one. Now, keep in mind that if you want to pass an argument to the closure in a filter, it is the third parameter to be passed! I found this out myself as my application continued to puke all over itself when I was passing a parameter to the filter and I couldn’t figure out why. So this is why you see both the route, the request, and our custom parameter in the third position like so:

Ok, everything is in place, let’s test it:

laravel filter parameter

Excellent! There are a few things to observe here. First off, it looks like these filters work just as well in stacking whether we are using the array as the second parameter syntax or the method chaining syntax. Also, notice that only the message from filter two and filter three were triggered. Why is this? This is because when we changed one:booey to one:potato in our routes file, filter one then noticed within it’s if clause that $baba was no longer equal to booey, it was equal to potato. Therefore, the filter one message did not trigger.

Other Ways to Assign Filters

There are additional ways we can assign filters to routes. Of course we could use the global option, but sometimes that may be too much. On the other hand, we may not want to have to attach a filter to many different routes. There are two ways to get around this. One is Group Filters and the other is Pattern Filters.

Group Filters

These are really slick. Basically, you just wrap all the routes that you want to have assigned a filter and, voila, you’re done. The syntax looks like this:

So here, what we do is to take the same routes we’ve been working with so far, and just wrap them within a Route group with the filter applied. Now when we visit these routes, our three filters will be triggered. Let’s visit the login route just to be sure:
laravel route group filters

Excellent, we can see that, yes, the login route loads up just fine and we see at the top of the page that all three filters did fire before the request. There are all kinds of ways to define and apply filters, just have a look at the docs for the full comprehensive list.

Define Filters in a Class

In this tutorial, all of the filters have been set up in app/filters.php. You can also create your own class to handle this. Remember in the laravel cache tutorial we created our own class, registered it with the IoC Container in the filters.php file, then made use of psr-4 to autoload the class for us. Either way works, and if fact this reminds me of one of the features of Laravel. This is that with almost all aspects of the framework, there are multiple ways to accomplish the same end goal. For this reason, you’ll have to kick the tires so to speak for some time before you find the approaches that work best for you!

Using Filters with Controllers

Most likely your application will be making use of controllers. So far we have not looked at how to assign filters to controllers in Laravel. It’s really pretty much the same approach, so once you understand the concept of assigning filters via your routes.php file, it’s an easy task to translate those skills to applying these same filters to controllers instead. You can also embed the filter logic right into your controller itself. Again, very flexible! You’ll need to experiment with the various approaches to see what you like best. For clarity, this is how you would do it:

Laravel Filters Conclusion

The takeaway with filters is that they allow you to nicely package up the rules for accessing routes, handling before request logic, as well as after request logic into manageble pieces of code. That way you are able to better keep things DRY, by making use of your various filters in different places in the application. Almost all application are going to need filters, so we need to be familiar with them. After reading this episode, head on over to the official docs and test out all the examples in your own sandbox to get used to using them.