Ansaf Ans
Ansaf Ans

Reputation: 91

Eloquent hasOne relationship return null

I have 2 models Admin and Subscription

Model Admin.php

public function subscription() {
    return $this->hasOne('App\Subscription','admin_id','id'); 
}

Model Subscription.php

public function payer() {
     return $this->belongsTo('App\Admin','admin_id','id');
}

When i try to get payer of the subscription it returns null. I am getting a payer like this.

In Controller.php

$subscriptions=Subscription::all();

foreach ($subscriptions as $subscription) {
    dd($subscription->payer);
}

Please give me a solution. I tried and change everything it's still not working.

This is my migrations

Subscription Table

id  int(10) unsigned Auto Increment  
subscription_type   varchar(191) NULL    
expiry_date timestamp NULL   
status  varchar(191) [required]      
admin_id    varchar(191)     
created_at  timestamp NULL   
updated_at  timestamp NULL

Admin Table

id  int(10) unsigned Auto Increment  
name    varchar(191)     
email   varchar(191)     
password    varchar(191)     
remember_token  varchar(100) NULL    
created_at  timestamp NULL   
updated_at  timestamp NULL

Upvotes: 0

Views: 4837

Answers (3)

Mohad Hadi
Mohad Hadi

Reputation: 1986

the method name you write for hasOne must have more than 3 chars.

Upvotes: 0

basil
basil

Reputation: 11

Laravel pitches a fit if you don't use a number as an id. You have to tell it if you use a string.

protected $keyType = 'string';

Upvotes: 1

Pol Lluis
Pol Lluis

Reputation: 1162

Im not sure since you haven't showed your migration files but I think you might be setting the relation wrongly, you are specifying the same foreign. Also if primary key is named 'id' you don't need to specify it. So maybe this works out:

Model Admin

public function subscription()
{
  // asumes foreign key is called admin_id
  return $this->hasOne('App\Subscription');
}

Model Subscription

public function payer()
{
  // asumes foreign key is called subscription_id
  return $this->belongsTo('App\Admin');
}

Update, if you have your tables named as you are suggesting you won't need to specify any key because you are following laravel default naming conventions.

Upvotes: 2

Related Questions