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

waqaar541's avatar

Convert sql query to laravel query builder

This is the sql query

I have four tables answers, questions, users ans upvote_answers. I get the result by joining three tables answers, questions and users . But i also wanna know for logged in user where he has upvoted an answer or not.

SELECT answers.answer_content as answer_content, answers.created_at as answer_upvote, answers.created_at as answer_downvote, questions.question_title as question_title, questions.question_slug as question_slug, users.name as user_name, upvote_answers.upvote as upvote FROM answers JOIN questions on questions.id = answers.question_id JOIN users on users.id = answers.user_id LEFT JOIN upvote_answers ON upvote_answers.answer_id = answers.id AND upvote_answers.user_id = '2' WHERE questions.question_active = 1 and answers.answer_active = 1

Thank you

0 likes
4 replies
shez1983's avatar

you probably need to look into relationships and see if that will help

santhusurya's avatar

@waqaar541 I would like to suggest you to make use of Raw Expressions option provided within Laravel Query Builder.

This will allow you to use current query with use of Raw Methods listed under Raw Expressions with slight modifications.

Please or to participate in this conversation.