greents
greents

Reputation: 25

Can't access to laravel hasone relation method from controller

I am struggling with the relation hasOne. here is what I have

User model:

class User extends Authenticatable
{
   use Notifiable;
   public function candidat()
   {
      return $this->hasOne('App\Model1');
   }

   public function element ()
   {
      return $this->hasOne('App\Model2');
   } 
}

Model1 class:

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

Model2 class:

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

Controller class:

public function savingcandidat(CandidatRequest $requete){
    $candidat = $this->candidatSave($requete);
    $user = User::query()->where('email',$requete->email)->get(); //there i get the user
   //here is where i get the error : "Method Illuminate\Database\Eloquent\Collection::candidat does not exist."
    $user->candidat()->save($candidat);
}

I get the error:

"Method Illuminate\Database\Eloquent\Collection::candidat does not exist."

when I use tinker it works properly, thank you in advance for your help

Upvotes: 1

Views: 747

Answers (1)

aimme
aimme

Reputation: 6773

$user = User::query()->where('email',$requete->email)->get(); 

This will return a collection result and it will not have that model/builder method. use first() instead of get if it's just one record

Like this

$user = User::query()->where('email',$requete->email)->first();

Upvotes: 1

Related Questions