[Fixed] How to use Laravel @can() in Angular


I have a project that is fully Laravel-8 using Spatie-Permission. Everything is working well.

But the team decided to use Laravel-8 as backend and Angular-11 as front-end.

Initially, in the pure Laravel, it looks like this:


public function index()
     if (! Gate::allows('role_access')) {
        return abort(401);
    $roles = Role::all();

    return view('admin.roles.index', compact('roles'));

view blade:

<li class="nav-item">
  <a href="{{ route(" admin.roles.index ") }}" class="nav-link {{ request()->is('admin/roles') || request()->is('admin/roles/*') ? 'active' : '' }}">
    <i class="nav-icon fas fa-briefcase"></i>

Now that I’ve transformed the front-end into Angular, I have:

public function index(Request $request)
        return response()->json([ "message" => 'User do not have permission'], 401);
    if(($request->get('sort')!='null' && $request->get('sort')!='') && $request->get('search')) {
        $role = Role::with('permissions')->where("name", "LIKE", "%{$request->get('search')}%")->orderby($request->get('sort'), $request->get('order'))->paginate(10);
    } else if(($request->get('sort')!='null' && $request->get('sort')!='')){
        $role = Role::with('permissions')->orderby($request->get('sort'), $request->get('order'))->paginate(10);
    else if($request->get('search'))
        $role = Role::with('permissions')->where("name", "LIKE", "%{$request->get('search')}%")->paginate(10);
        $role = Role::with('permissions')->paginate(10);
    return response()->json($role, 200);

When it was purely Laravel, I used @can() for the aspect users should only see. For instance only users with that have permission to role_access will see it.

How do I transform @can() in Laravel view blade into Angular?



you can get all the permission from login user like this

$permissions = auth()->user()?->role()->with('permissions')->get()
return $permissions;

then in javascript side angular ,react or vuejs you can create a helper like this

const can = (permissions, can) => {
    if (permissions) {
        return permissions.some(r => can.includes(r))

    return false;

then you can use anywhere can(permissions,'read_pust') here permissions is get from server and store in cookie or localstorage

EX: i use this v-if="$helpers.can(permissions, ['node_read'])" this in vuejs you can create helper like this

Leave a Reply

(*) Required, Your email will not be published