Undefined property: IlluminateDatabaseEloquentRelationsBelongsToMany::$balance

  laravel, laravel-5.8, many-to-many, php, pivot-table

I have a Many to Many relationship between Wallet & User Models:

User.php:

public function wallets()
    {
        return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
    }

Wallet.php:

public function users()
    {
        return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id')->withPivot('balance');
    }

And the pivot table user_wallet goes like this:

enter image description here

Now I need to get the name of wallets and the balance of that wallet in a table at Blade.

So at the Controller, I added this:

public function index($id)
{
   // $id is the user id
   $userWallet = Wallet::with("users")->whereHas('users',function ($query)use($id){
      $query->where('user_id',$id);
   })->get();
}

And then at the Blade:

@forelse($userWallet as $wallet)
   <div class="message_fullName">
   {{ $wallet->name }}
   </div>

   <div class="message_tag">
   {{ $wallet->users()->balance }}
   </div>
@empty
   Empty
@endforelse

But I get this error:

Undefined property: IlluminateDatabaseEloquentRelationsBelongsToMany::$balance

So what’s going wrong here? How can I properly get the balance at the pivot table?

I would really appreciate any idea or suggestion from you guys..

Thanks in advance.

Source: Laravel

Leave a Reply