Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

channaveer's avatar

Query and fetch polymorphic table realted relations in Laravel

I have the following tables

payments
---------
id, user_id, payable_id, payable_type, status

Payable can be of type User Subscriptions / Courses Registered and something else too

course_categories
---------------
id, name, slug

courses
-------
id, name, currency_id, price, course_category_id, language_id

I want to query all the payments made by login user and with status success which can be done with the following

$payments = Payment::where([
        'user_id' => $user->id,
        'status' => 'success'
    ])
    ->get();

But I need all the relationship records too like the following

$payments = Payment::with(['courses', 'courses.courseCategory])
    ->where([
        'user_id' => $user->id,
        'status' => 'success'
    ])
    ->get();

The following with Payable works but I need the relations of payable

$payments = Payment::with(['payble'])
    ->where([
        'user_id' => $user->id,
        'status' => 'success'
    ])
    ->get();

How can I achieve it? If I do as ['payable'] then it returns the respective records. But I need payables courses or course_category

0 likes
2 replies

Please or to participate in this conversation.