0
 $credits = User::select('id','username')->where('id', auth()->id())
          ->with(['game_credits' => function($query) use ($phase){
           $query->select('user_id','no_of_game_played','game_credits')
             ->where('phase_id', $phase->id);
          }])->first();

Here I want to return game_credits-no_of_game_played which will give me the remaining credits, How can I do that inside whereHas? Here, USER HAS MANY GAME CREDITS

Nis shres
  • 39
  • 5

1 Answers1

0

Maybe instead of using the user model you can call the game credit model and assign whereHas to the user model. Game credit model considered as GameCredit. ex:

Assign user id to variable:

$user_id = auth()->user()->id;

Sum Game Credits:

$game_credits = GameCredit::select('no_of_game_played','game_credits')
->where('phase_id', $phase_id)
->whereHas(['users'] => function($query) use ($user_id)){
       $query->select('id','username')
         ->where('id', $user_id);
      }])->sum('game_credits');

Sum no of game played:

$no_of_game_played = GameCredit::select('no_of_game_played','game_credits')
->where('phase_id', $phase_id)
->whereHas(['users'] => function($query) use ($user_id)){
       $query->select('id','username')
         ->where('id', $user_id);
      }])->sum('no_of_game_played');

The Credits:

$credits = $game_credits - $no_of_game_played;

I hope this will help you. Thanks!

Amri
  • 77
  • 8