1

I have three models as per the code below.I have a problem of returning a single savings data for authenticated users. Any help will be highly appreciated. I want a low like this:

$savings =Savings::client()->client_users()->where('user_id', '=', Auth::user()->id)->get();

Savings Model

class Savings extends Model
{
   
    public function client()
    {
        return $this->hasOne(Client::class, 'id', 'client_id');
    }

}

Client Model

 class Client extends Model
    {
       
        public function client_users()
    {
        return $this->hasMany(ClientUser::class, 'client_id', 'id');
    }
    
    }

Client User Model

class ClientUser extends Model
    {
       
    public function user()
       {
        return $this->hasOne(User::class, 'id', 'user_id');
        }
    
    }
Kevin Otieno
  • 55
  • 1
  • 10

2 Answers2

1

You can try this query:

$user = Auth::user();

return Savings::whereHas('client.client_users', function ($query) use ($user){
    $query->where('user_id', $user->id);
}])->get();
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

I have fixed the above error. Thanks @Maik Lowrey

 $user = Auth::user();
    
$savings= Savings::whereHas('client.client_users', function ($query) use ($user){
                $query->where('user_id', $user->id);
            })->get();
            return response()->json($savings);
            //return response($savings);
Kevin Otieno
  • 55
  • 1
  • 10