Skip to content

Instantly share code, notes, and snippets.

@anaxamaxan
Created April 1, 2014 04:00
Show Gist options
  • Save anaxamaxan/9907466 to your computer and use it in GitHub Desktop.
Save anaxamaxan/9907466 to your computer and use it in GitHub Desktop.
args in a Laravel 4 auth filter
<?php
// in my controller constructor, I apply a filter with arguments:
$this->beforeFilter('auth.hasRole:admin,staff,developer', ['except' => 'getLogoutas',]);
// in my global filters.php
/**
* Verify that the logged-in user has a specified role
*/
Route::filter('auth.hasRole', function($route, $request, $value)
{
if (! Auth::check() OR ! Auth::user()->hasRole($value)) {
return Response::json(['flash' => __('application.access_denied'),],403);
}
});
// in User.php model (this could easily be a trait or abstracted to a service)
public function hasRole($key)
{
return $this->hasAnyRole(explode(',',$key));
}
public function hasAnyRole($keys)
{
if( ! is_array($keys))
{
$keys = func_get_args();
}
foreach($this->roles as $role)
{
if(in_array($role->keyname, $keys))
{
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment