How to get username from user_id in laravel?

I have 2 table 1st fund2nd usersI have a registered member name in the table usersand a registered member in the fundtable user_id. I want to show the username in a table where I can show it user_id.

<div class="deposit-body">
    <table class="table main-table">
        <tbody>
            <tr class="head">
                <th>Name</th>
                <th>Date</th>
                <th>Currency</th>
                <th>Amount</th>
            </tr>
            @foreachFund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get()
                <tr>
                    <td>{{ $fund->user_id }}</td>
                    <td>{{ $fund->updated_at}}</td>
                    <td><strong>{{$basic->currency}}</strong></td>
                    <td><strong>{{ $fund->total }}</strong></td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>

I applied the following code to my foundation model. But that does not work.

public function user(){
    return $this->belongsTo('App\User', 'user_id'); 
}
+4
source share
2 answers

Use relationshipto access the user object.

@foreach(Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get() as $fund)
 <tr>
        <td>{{ $fund->user->name }}</td>
 </tr>
@endforeach
0
source

It seems that not all funds have been filled user_id. In this case, you should use optional()an assistant.

Move the logic to the controller:

$funds = Fund::with('user')->where('created_at', '>', Carbon::now()->subHours(24))->orderBy('id', 'desc')->take(10)->get();
return view('your.view', compact('funds'));

Then in the view:

@foreach ($funds as $fund)
    {{ optional($fund->user)->name }}
@endforeach
0
source

Source: https://habr.com/ru/post/1692484/


All Articles