2

I want to filter my query and return only if the user hasRole "Premium" and limit the result to 10.

Along with this query is a count of records which Conversion has and sort it in DESC order by total column.

Right now I have a working query that returns the count of Conversion and with a User but without user filter Role.

// Model Conversion belongs to User
// $from & $end uses Carbon::createDate()
// Current code
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
                ->whereBetween('created_at', [$from,$end])
                ->where('type','code')
                ->where('action','generate')
                ->whereNotNull('parent_id')
                ->with('user')
                ->groupBy('user_id')
                ->orderBy('total', 'DESC')
                ->take(10)
                ->get();

// current result
foreach ($query as $q) {
    $q->user->name; // To access user's name
    $q->total; // To access total count
}

// I tried this but no luck
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
                ->whereBetween('created_at', [$from,$end])
                ->where('type','code')
                ->where('action','generate')
                ->whereNotNull('parent_id')
                ->with('user', function($q) {
                    $q->hasRole('Premium');
                })
                ->groupBy('user_id')
                ->orderBy('total', 'DESC')
                ->take(10)
                ->get();
moreishi
  • 63
  • 7

2 Answers2

1

Use the whereHas() instead of with(). Also, you can't use hasRole() if it's not a local scope:

->whereHas('user.roles', function($q) {
    $q->where('name', 'Premium');
})
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

You need to use whereHas instead of with, like this:

 ->whereHas('user', function ($query) {
       $query->where('role','Premium');
 })
Alex
  • 2,707
  • 4
  • 29
  • 42