A powerful feature of Laravel is adding filters that can run both before and after a request is made to our application. In this recipe, we'll explore these filters.
To complete this recipe, follow these steps:
In our
routes.php
file, add a route only accessible to admins with filters attached:Route::get('admin-only', array('before' => 'checkAdmin', 'after' => 'logAdmin', function() { return 'Hello there, admin!'; }));
Add in the two filters in our
filters.php
file:Route::filter('checkAdmin', function() { if ('admin' !== Session::get('user_type')) { return 'You are not an Admin. Go Away!'; } }); Route::filter('logAdmin', function() { Log::info('Admin logged in on ' . date('m/d/Y')); });
Create a route where we can set the admin session:
Route::get('set-admin', function() { Session::put('user_type', 'admin'); return Redirect::to('admin-only'); });
Test...