Happy Coder
Happy Coder

Reputation: 4682

Role based ACL in Laravel

I am implementing a role based ACL for an API and I have tables for users, roles, pages, page actions(view, add,edit,delete) and role associations with page actions. Now how can I write a Gate or Policy for Authorizations utilizing these tables and use it in a middleware? Any example is welcome.

I went through the Authorization documentation, but not getting an idea of how to define abilities and check for them in a role based scenario.

Upvotes: 0

Views: 307

Answers (1)

Joeri
Joeri

Reputation: 151

Have a look at this source code as example: Spatie/Laravel-permission

Also an example for a middleware to check role or permission:

can.php

public function handle($request, Closure $next, $permission)
{       
    if(!$request->user()->can($permission)){
        flash()->warning(trans('alert.noAccess'));
        return abort(403);
    }

    return $next($request);
}

role.php

public function handle($request, Closure $next, $role, $permission = null)
{
    if (auth()->guest()) {
        return redirect(route('auth.login'));
    }

    if (!$request->user()->hasRole($role)) {
        abort(403);
    }

    return $next($request);
}

Upvotes: 1

Related Questions