I want to get a value of balance column from a pivot table called user_wallet which goes like this:
So I wrote this at the Controller:
$bal = Wallet::with("users")->whereHas('users', function ($query) use ($wallet_id, $user_id) {
$query->where('wallet_id', $wallet_id);
$query->where('user_id', $user_id);
})->first();
But when I do dd($bal->balance), I get null!
So why is that? How can I get the balance value based on user_id and wallet_id properly?
Here is also the relationships between User model and Wallet model:
User.phppublic function wallets()
{
return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')->withPivot('balance');
}
Wallet.phppublic function users()
{
return $this->belongsToMany(User::class, 'user_wallet', 'wallet_id', 'user_id');
}
I would really appreciate any idea or suggestion from you guys...
Your query is supposed to be like below. Becuase the relation you're making is with users table not user_wallet.
$bal = Wallet::with("users")
->whereHas('users', function ($query) use ($user_id) {
$query->where('id',$user_id);
})
->where('id', $wallet_id)
->first();
You can make a simple query as well:
$bal = DB::table('user_wallet')
->where('wallet_id', $wallet_id)
->where('user_id', $user_id)
->first();
if (!empty($bal)) {
$balance = $bal->balance;
}
Since it is a many to many relationship, for getting the pivot table you loop like below:
@foreach($bal as $key => $value)
{{$value->pivot->balance}}
@endforeach
or if it is a single item then you can do like:
$user = $bal->users()->first();
$user->pivot->balance;
or
$user = $bal->users->first();
$user->pivot->balance;
if still need directly then, as suggested by @Dilip Hirapara answer.