tariqul anik
tariqul anik

Reputation: 324

How to get data from belongsTo laravel

I have 2 tables Users, Organization

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

Upvotes: 0

Views: 2606

Answers (1)

lagbox
lagbox

Reputation: 50481

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();

Upvotes: 3

Related Questions