Search code examples
phplaravellaravel-4packagebefore-filter

How can a Laravel package filter all requests and redirect if necessary?


I would like to build a package for Laravel 4 that checks for some specific parameters and redirects the request to another url if needed.

Is there a best way to do that?

I would prefer to have the package able to simply be dropped in and configured without having to modify the filters or routes files in the base Laravel install.


Solution

  • How to do it simply put:

    You can do a pre request processing by registering before application events to for a global filtering of responses sake like so:

    App::before(function($request)
    {
        //
    });
    

    You have to register it in one of your start files or in a service provider.


    Package recommended for study:

    I strongly recommend you to delve into Laravel-Hooks, a Laravel 4 package by Chuck Heintzelman.

    You should focus on the app/start/onbefore.php hook, executed as global app "before" filters.

    Excerpt:

    /**
     * Set up before listener if found
     */
    protected function registerOnBefore()
    {
        $file = $this->hookName('onbefore');
        if ($file)
        {
            $this->app->before(function ($request) use ($file)
            {
                $result = static::load($this->app, $file, compact('request'));
                if ($result !== 1)
                {
                    return $result;
                }
            });
        }
    }
    

    Stripped from Laravel-Hooks/src/Heintzelman/LaravelHooks/LaravelHooksServiceProvider.php.

    Don't forget to share your findings :-)