Mehdi El Aissi
Mehdi El Aissi

Reputation: 123

Condition with a relationship eloquent

Hello Im a beginer with Laravel Im trying to retrieve the data using eloquent but I have to add a condition linked to a relationship my model

class DemandeInscription extends Model
{
    public function user(){
        return $this->belongsTo('App\User','tuteur_id');
    }
}

And here is what I tried in my Controller

$demandes= DemandeInscription::with('user','meet','enfant')
           ->where('confirmation','=',0)->user()
           ->where('phone_verified_at','!=',null)
           ->orderBy('created_at','desc')->paginate(10);

i get the error

Arguments
"Call to undefined method Illuminate\Database\Eloquent\Builder::user()"

Upvotes: 1

Views: 46

Answers (1)

Akhtar Munir
Akhtar Munir

Reputation: 1769

Well you can get it in this way

$demandes= DemandeInscription::with(['user' => function($query){
              $query->where('phone_verified_at','!=',null);
           },'meet','enfant'])
           ->where('confirmation','=',0)
           ->orderBy('created_at','desc')->paginate(10);

OR

$demandes= DemandeInscription::whereHas(['user' => function($query){
              $query->where('phone_verified_at','!=',null);
           }])
           ->orwhereHas('meet','enfant')
           ->where('confirmation','=',0)
           ->orderBy('created_at','desc')->paginate(10);

OR with Local Scope, inside User Model write this scope

public function scopeVerified($query){
   return $query->where('phone_verified_at','!=',null);
}

$demandes= DemandeInscription::with(['user' => function($query){
              $query->verified();
           },'meet','enfant'])
           ->where('confirmation','=',0)
           ->orderBy('created_at','desc')->paginate(10);

Upvotes: 1

Related Questions