Search code examples
phpmysqllaraveleloquentrelational

How do you filter the user with hasRole() in Laravel 5 within relational query?


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();

Solution

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

     ->whereHas('user', function ($query) {
           $query->where('role','Premium');
     })