简体   繁体   中英

How to retrieve data through Foreign Key in Laravel?

How to retrieve data in Laravel.

I am having table user in which I m having field parent_id in which I m showing information of its user_id.

Now I want to show information of logged user

I tried this

 {{Auth::user()->parent_id}}

I get the selected parent_id, now I want the name of that user_id.

I'm trying this

{{(Auth::user()->parent_id)->value('name')}}

Its getting an error. Please tell me how can I write this in my code to get name of that parent id.

Define the relationship to the parent user in the User modal.

User Modal

public function parent()
{
    return $this->belongsTo(User::class, 'parent_id');
}

blade

{{ Auth::user()->parent->name }}

There are (at least) two ways to do that.

1- Without relationship: you can select/find the user by parent_id and get its name. Something like this:

{{ App\User::find(Auth::user()->parent_id)->name }}

2- With relation: and I think it is easier. Define the relationship and set the parent_id as foreign key. Then you can get the parent user. Something like this:

{{ Auth::user()->parentUser->name }} // parentUser is the method created in User model 

To define and use the relationship see the @Tharaka Dilshan answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM