Jesús Cova
Jesús Cova

Reputation: 339

Relation One to One comes Null with Laravel

I am using Eloquent to create the queries but I have a relation One to One and I am trying to get the data and it returns null.

My models are:

//Customer:

class Customer extends Model
{
   protected $table = 'customers';

   protected $primaryKey = 'rut';

   public function user() {
        return $this->hasOne(User::class, 'rut');
  }
}

//User:

class User extends Authenticatable
{
   use Notifiable;

   protected $primaryKey = 'rut';

   public function customer()
   {
      return $this->belongsTo(Customer::class, 'rut');
   }
}

And I am doing my query like this:

$customers = Customer::with('user')->paginate(10);

It returns data but the user data is null:

activity: "Particular"
address: "AV. GRECIA 690 LOC 5"
commune_id: 12
created_at: null
email: "[email protected]"
phone: null
rut: 4180753
updated_at: null

user: null

So I wonder how can I fix it? I mean why does it come null in user? what can the problem be?

Thanks!

Upvotes: 0

Views: 375

Answers (1)

OMR
OMR

Reputation: 12218

You Make the relation one to one in the wrong way:

Customer belongs to a User Not the opposite ..

class User extends Authenticatable
{
   use Notifiable;

   protected $primaryKey = 'rut';

   public function customer()
   {
      return $this->hasOne(Customer::class, 'customers.rut','users.rut');
   }
}

class Customer extends Model
{
   protected $table = 'customers';

   protected $primaryKey = 'rut';

   public function user() {
        return $this->belongsTo(User::class, 'customers.rut','users.rut');
  }
}

Upvotes: 1

Related Questions