Reputation: 137
hellow i want to show 10 persons who has deposited amount in last24 hours . i am able to show there user_id and amount but i want users name instead of user_id.
i have no name colum in $funds it is in users i have this code:
<div class="col-md-6">
<div class="text-center"><h4 class="text-success">Last 10 Investors</h4></div>
<table class="table text-white" >
<tbody>
@foreach( \App\Fund::where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund->user_id }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>@endforeach
</tbody>
</table>
</div>
Upvotes: 0
Views: 1719
Reputation: 7972
Set up a relation from your Fund Model to the User Model
In your Fund model,
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
and you could access the User that belongs to the fund as
$fund->user->{your-username-field}
OR if you don't want to set up a relationship and fetch the username, you could do so by
$user = \App\User::find($fund->user_id);
if (! empty($user)) {
$user_name = $user->user_name; // or whatever the username field is
}
Upvotes: 4
Reputation: 1213
so you have to models: "Fund" and "User".
you should connect them with Laravel's Relationships:
add this method to "User" model:
public function funds()
{
return $this->hasMany('App\Fund', 'user_id');
}
then in "Fund" model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
now you can access user's name from funds:
i suggest you to retrive your datas in controller, not views:
public function index()
{
$funds = Fund::with('user')->
where('created_at', '>', \Carbon\Carbon::now()->
subHours(24))->orderBy('id', 'DESC')->take(10)->get();
return view('viewName', ['funds' => $funds]);
}
then in view:
@foreach ($funds as $fund)
{{ $fund->user->name }}
@endforeach
Upvotes: 0
Reputation: 697
Try like this :
@foreach( \App\Fund::select("*")->with('users')->where('created_at', '>', \Carbon\Carbon::now()->subHours(24))->orderBy('id', 'DESC')->take(10)->get()->toArray() as $fund)
<tr>
<th scope="row"></th>
<td>{{ $fund['user']['user_name'] }}</td>
<td class="text-center text-warning">{{ $fund->total }}</td>
<td class="text-right"><img src="https://adsok.com/img/btc.png" alt="Bitcoin"> <i><b>bitcoin</b></i><br></td><br>
</tr>@endforeach
Upvotes: 1