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

jmatchett123's avatar

SQL query not working in laravel

Hi, This query works absolutely fine in sql

SELECT * FROM lessons LEFT JOIN (SELECT * FROM progress WHERE user_id = '5' GROUP BY user_id) progress ON lessons.lesson_id = progress.lesson_id

However when I try to convert it to laravel, it doesn't work. Am I doing anything wrong?

$data = DB::table('lessons') ->leftjoin( DB::raw("SELECT * FROM progress WHERE user_id = '5' GROUP BY user_id"), 'lessons.lesson_id', '=', 'progress.lesson_id') ->get();

Thanks

0 likes
5 replies
jmatchett123's avatar

I am not getting errors but the page is not showing all of the data that I want it too. It shows some but not all

jlrdw's avatar

Look over this for example, try not to use raw:

$bindings = [
    'product_type_id' => 1,
    'service_sub_type_id' => 2,
    'school_id' => 57,
    'status_id1' => 2,
    'status_id2' => 3
];

$users = DB::select('SELECT DISTINCT CONCAT(u.last_name, ", ", u.first_name ) AS full_name, ci.created_at AS date_purchase
FROM cart_items AS ci
LEFT JOIN products AS p ON ci.product_id = p.id
LEFT JOIN carts AS c ON ci.cart_id = c.id
LEFT JOIN `status` AS s ON ci.status_id = s.id

INNER JOIN users AS u ON c.user_id = u.id
INNER JOIN school_users AS su ON u.id = su.user_id

INNER JOIN
    (
    SELECT MAX(created_at) AS created_at1, cart_id
    FROM cart_items
    GROUP BY `cart_id`
    )p2 ON ci.cart_id = p2.cart_id AND ci.created_at = p2.created_at1

WHERE p.product_type_id = :product_type_id AND p.service_sub_type_id = :service_sub_type_id AND su.school_id = :school_id AND ci.status_id = :status_id1 OR ci.status_id = :status_id2
ORDER BY ci.created_at DESC', $bindings);

From an older post from @cronix Notice no raw.

kleeh's avatar

I like @jlrdw 's solution. I mean, if one already has a regular SQL query that is working I don't see the point in doing the extra work it takes to convert it using some sort of ORM or query builder. If you tried his solution and it gives you the desired results, you should probably mark it as the Best Answer.

jlrdw's avatar

If using regular sql, make sure to properly bind parameters.

Please or to participate in this conversation.