laravel Eloquent relationship using Distinct

17,252

When you access an Eloquent relationship like a property, you will get an Eloquent Collection. However, distinct() is a Query Builder method and you need access to the Query Builder instance before returning the Collection. If you add () to the end of the relationship, you gain access to the Query Builder instance and can chain those Query Builder methods. In your case, you are actually looking for the groupBy() method and not distinct(). Don't forget to end the query with get().

foreach ($pochette->Journees()->groupBy('formateurs_id')->get() as $formateur) {
    echo $formateur->id ;
    echo "<br>";
}
Share:
17,252
Ayed Mohamed Amine
Author by

Ayed Mohamed Amine

I am a web developper.

Updated on June 04, 2022

Comments

  • Ayed Mohamed Amine
    Ayed Mohamed Amine almost 2 years

    I need show data with relationship using DISTINCT.

    This is my sql data :

    table pochettes

    id | 
    49 |
    

    table journees

    id | formateurs_id | pochettes_id
    1  | 3             | 49
    2  | 4             | 49
    3  | 3             | 49
    

    table formateurs

    id | 
    3  |
    4  |
    

    model Pochette

    public function Journees()
    {
        return $this->hasMany('App\Journee','pochettes_id');
    } 
    

    model Journee

    public function Formateurs()
    {
        return $this->belongsTo('App\Formateur', 'formateurs_id');
    }
    

    I am used this code to show data with distinct formateurs because a Formateur can have many Journee in the same Pochette :

    $pochette = Pochette::find(49);
    foreach ($pochette->Journees->distinct('formateurs_id') as $formateur) {
                echo $formateur->formateurs_id;
                echo "<br>";
            }
    

    But this code dosn't work, I have this error message

        **BadMethodCallException in Macroable.php line 81:
    Method distinct does not exist.**
    

    I would show this result :

    3
    4
    

    not :

    3
    4
    3