Search code examples
phplaravelmany-to-manypivot-tablelaravel-5.8

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$balance


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: Illuminate\Database\Eloquent\Relations\BelongsToMany::$balance

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


Solution

  • You have to loop user

    @forelse($userWallet as $wallet)
       <div class="message_fullName">
       {{ $wallet->name }}
       </div>
    
       <div class="message_tag">
        @if(isset($wallet->users)&&count((array)$wallet->users))
          @foreach($wallet->users as $user)
            {{$user->pivot->balance }}
          @endforeach
        @endif
       </div>
    @empty
       Empty
    @endforelse
    

    Your query should be

    $userWallet = Wallet::with(["users"=>function ($query)use($id){
          $query->where('user_id',$id);
       }])->whereHas('users',function ($query)use($id){
          $query->where('user_id',$id);
       })->get();