0

I have an 'Admin' model which has a manyToMany relationship with a 'Priv' model. There is a pivot table named 'admins_privs' which links the two together, as many Admin's can have many privileges.

What I need to do is to be able to do (in Blade) is to check if the logged in Admin has a certain priv (by ID) and if true, display something. I thought about adding a function in the admin model as such:

// Admin.php

public function HasPriv($priv_id)
{
    // Need help here!!!   
}

Then I can call this function in my blade templates as such:

// BLADE TEMPLATE

@if (Auth::guard('admin')->user()->HasPriv(1))
DO SOMETHING
@endif

What do i need to add into the first block of code, to search the many to many relationship to see if the user is linked to a Priv.

Any help would be appreciated.

Thanks M

finlamit
  • 49
  • 4

1 Answers1

0

A pivot table is related to two model, thus it has two foreign-keys. For your case, admins_privs table will have and admin_id and an priv_id. So, if you want to take/get specific privilege that belongs to a specific admin, you need to pass two keys (admin_id and priv_id) to controller. Or maybe take the admin_id inside controller from auth().

admin_controller:

public function HasPriv($priv_id,$admin_id)
{
    $pivot = DB::table('admins_privs')
            ->where(admin_id,$admin_id)
            ->where(priv_id,$priv_id)
            ->get()->first();

    return $pivot; // will be null if admin does not have the privilege
}
Farhan Ibn Wahid
  • 926
  • 1
  • 9
  • 22