There’s a section on the dashboard that displays Top Customers by Revenue.
By default, this section shows leads and revenue from all users, but I want to restrict it so that:
-
Non-admin users only see leads assigned to themselves (leads.user_id = auth()->id()).
-
Admin users (role_id = 1) can still see all leads without any restriction.
Scenario:
The main models involved are Person and Lead.
Each record in the leads table has a user_id field that identifies the owner of that lead.
What I’ve tried so far:
I added logic so that only specific users can view their own data.
public function getTopCustomersByRevenue($limit = null)
{
$tablePrefix = DB::getTablePrefix();
$user = auth()->user();
$query = $this->personRepository
->resetModel()
->leftJoin('leads', 'persons.id', '=', 'leads.person_id')
->select('*', 'persons.id as id')
->addSelect(DB::raw('SUM('.$tablePrefix.'leads.lead_value) as revenue'))
->whereBetween('leads.closed_at', [$this->startDate, $this->endDate])
->having(DB::raw('SUM('.$tablePrefix.'leads.lead_value)'), '>', 0)
->groupBy('person_id')
->orderBy('revenue', 'DESC');
if ($user->role_id != 1) {
$query->where('leads.user_id', $user->id);
}
However, this does not seem to work correctly, even non-admin users still see leads belonging to other users.