Laravel DataTables queries and Entrust

204 Views Asked by At

I am using Laravel 5.3 with Laravel Datatables and Entrust

On my index action I display a list of records in a datatable. Now I need to integrate entrust in to it. If the user is an admin they can see all leads. However, if the user is a normal user the can only see the records that belong to them.

I'm not sure how to approach this, do I put this query in an if statement checking for roles or is there a better way?

public function query()
    {
        $leads = Lead::query()
            ->select([
                'leads.id as id',
                'leads.parent_id as parent_id',
                'statuses.name as status',
                'leads.title as title',
                'leads.first_name as first_name',
                'leads.last_name as last_name',
                'leads.opt_in as opt_in',
                'leads.created_at as created_at',
                'leads.user_id as user_id',
            ])
            ->leftJoin('statuses', 'leads.status_id', '=', 'statuses.id');

        return $this->applyScopes($leads);
    }
1

There are 1 best solutions below

0
On

Too long I don't use Entrust, because Laravel has Policies. But at your problem, I saw that Entrust has method

Auth::user()->can('permission-name');

You must create permission and save into DB which create by run command

php artisan entrust:migration

After create permission, apply it to user, it may have Admin permission and Normal User permission

Please read more at: https://github.com/Zizaco/entrust Hope I can help. If can use Entrust, let's research about Policies of Laravel, it's very good. Learn about Policies at https://mattstauffer.co/blog/acl-access-control-list-authorization-in-laravel-5-1#policies