I have a Many To Many relationship between User Model & Wallet Model:
Wallet.php :
public function users() {
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
And User.php :
public function wallets() {
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id');
}
And the pivot table
of this relationship goes like this:
So I can properly show Wallet name at the Blade:
@forelse($user->wallets as $wallet)
<tr>
<td>
{{ $wallet->name }}
</td>
<td>
{{ $wallet->balance }}
</td>
</tr>
@empty
<td colspan="5" class="text-center">
No wallet exist
</td>
@endforelse
But the wallet balance data does not appear (because it's in the pivot table and not the wallets
table).
So how to show this custom column in this case?
use withPivot
and mention additional column name
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
then in view
<td>{{ $wallet->pivot->balance }}</td>
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.