moyki
moyki

Reputation: 47

Filtering User Access to Routes by Role using Laravel

I have 2 different user roles, administrator and client.

How can I create a filter so that when a user is logged in the administrator role can access the routes that can create, update, delete, read while the client role can only access the read routes? Without using modules.

Upvotes: 0

Views: 192

Answers (1)

Jeemusu
Jeemusu

Reputation: 10533

You can achieve this by using route filters.

Route::filter('auth.isAdmin', function()
{
    // Get authenticated user
    $user =  Auth::user()

    if (!$user->isAdmin()) {

        // Redirect user away, display an error message, log attempt, whatever...
    } 
});

Create the isAdmin method in your User model:

public function isAdmin($permission)
{
   // if user has admin role
       // return true 
   // else
       // return false
}

You can now protect your pages by attaching the filter to the relevant routes.

Route::get('foo/bar', array(
    'before' => 'auth.isAdmin'
));

Upvotes: 2

Related Questions