Last Updated: September 09, 2019
·
5.21K
· searsaw

Laravel 4 Filters in Controllers

Filtering in Laravel 4 is extremely easy. In case you don't know what I'm talking about, a filter in Laravel is used on a particular route or set of routes to prevent certain people or actions from happening on a particular route. Laravel ships with a few simple but powerful filters to get you started. These include a filter to make sure a user is logged in and a one for protecting against CSRF attacks.

Typically, you would add these filters in your routes.php or filters.php. However, I feel that separating this code into another file away from the controller that it is protecting is cumbersome. I would rather put these filters in my controller so I can see at a glance what filters I have on certain routes. This can easily be done through the constructor of the controller. Let's check it out.

Let's pretend we have a resource controller that has a store method for storing a post into the database. We want to make sure this route is protected from CSRF attacks and should only be accessed by AJAX. This means we will need a filter for CSRF and for AJAX. The CSRF one comes with Laravel. Let's build one for AJAX. Insert the following code into routes.php

Route::filter('ajax', function()
{
    if (!Request::ajax()) App::abort(404);
});

Then we need to add these two filters to our controller through its constructor.

class PostController extends BaseController {

    public function __construct()
    {
        // Exit if not ajax
        $this->beforeFilter('ajax', array('only' => 'store'));
        // Exit if not a valid _token
        $this->beforeFilter('csrf', array('only' => 'store'));
    }

    public function store()
    {
        // Store like a boss
    }

}

This will now execute those two filters every time the store() method is called. If you wanted to make sure these filters were used on every call to this controller, then just omit the array passed as the second parameter to the beforeFilter() method.

That's it! As you can see, putting your filters in your controllers instead of in different files allows you to keep all logic in your controllers.