Home > OS >  (Eloquent) Show all the subscriptions of a client even if he has not made any payments
(Eloquent) Show all the subscriptions of a client even if he has not made any payments

Time:03-03

relationships

I have 4 tables, Clients, Plans, Subscriptions, and Payments.

I would like to get all the subscriptions of a client, his plan and if he has any payment made, I have tried this query, but it does not work as expected.

$data = Subscription::select('subscription_id')
            ->leftjoin('clients', 'clients.id', '=', 'subscriptions.client_id')
            ->leftjoin('plans', 'plans.id', '=', 'subscriptions.plan_id')
            ->leftjoin('payments', 'subscriptions.id', '=', 'subscriptions.id')
            ->where('clients.id', $id)
            ->get();

CodePudding user response:

If I were you, I'd utilize relationships and do it like this:

  • Create client to subscription relationship(1-to-many)
  • Create subscription to plan relationship(1-to-1)
  • Create subscription to payment relationship(1-to-many)

And then, the code to retrieve all will look like the following:

$client = Client::find($id);

$client->subscriptions()
    ->with(['plan', 'payments'])
    ->get();

To learn more about laravel relationships, check out this link: https://laravel.com/docs/9.x/eloquent-relationships

  • Related