How to get data from belongsTo laravel

2.3k views Asked by At

I have 2 tables Users, Organization

  • Users hasMany Organization
  • Organization belongsTo User

User.php

public function organization()
{
   return $this->hasMany(Organization::class, 'user_id');
}

Organization.php

public function user(){
    return $this->belongsTo(Organization::class,'user_id');
}

Now I want to retrieve data of Organization with user

In Controller

dd( Organization::with('user')->get() );

but in relation, user returns null. what should I do now? Please help

enter image description here

1

There are 1 answers

6
lagbox On BEST ANSWER

In the Organization model the user relationship should be a belongsTo with User not Organization(self).

public function user()
{
    return $this->belongsTo(User::class);
}

Then you can load that relationship on Organization:

$org = Organization::with('user')->get();