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

deepu07's avatar
Level 11

SQL query to Eloquent

hi mates, I was trying to convert from SQL query to Laravel eloquent. can anyone help me how to write this SQL query into eloquent? any help that would be great. thanks in advance.

SELECT
    *
FROM
    "messages"
    LEFT JOIN "message_phone" ON "messages"."id" = "message_phone"."message_id"
    LEFT JOIN "phones" ON "message_phone"."phone_id" = "phones"."id"
    LEFT JOIN "phone_user" ON "phone_user"."phone_id" = "phones"."id"
WHERE
    "phone_user"."user_id" = 10;


SELECT
    *
FROM
    "messages"
    LEFT JOIN "message_email" ON "messages"."id" = "message_email"."message_id"
    LEFT JOIN "emails" ON "message_email"."email_id" = "emails"."id"
    LEFT JOIN "users" ON "users"."email_id" = "emails"."id"
WHERE
    "users"."id" = 10;
0 likes
2 replies
willvincent's avatar

Could be implemented with the query builder, but that'd largely just be replicating the raw queries you have here in a potentially more obtuse way.. but basically you'd do all the joins onto the root model query, and then just select the bits you actually care about, in this case most likely that'd be messages.*

Better solution though, probably would be to leverage something like this which apparently allows you to establish a "manyThrough" relationship through your existing many:many relationship.

The bonus there would be that you'd effectively just be able to do something like this afterward:

$user = User::where('id', 10)->with(['phoneMessages', 'emailMessages']);

Please or to participate in this conversation.