phplaraveleloquenteloquent-relationshiplaravel-models

how to get unique data from database using eloquent model (laravel)


here is my code -

$list = Plot::active()
             ->whereNotNull('user_id')
             ->distinct('user_id')
             ->with('user')
             ->paginate(10);

but here "distinct('user_id')" not working. I want only unique user_id.


Solution

  • I solved the problem in this way -

    $list = User::has('plots')->whereHas('plots', function ($query) {
                $query->active();
            })->with('plots')->paginate(10);
    

    user - hasMany plots (one to many relationship)

    plot - belongsTo user (many to one relationship)