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

UsmanBasharmal's avatar

Using raw sql in laravel

I want to get a total of books by their Names from two tables one is a books table and the second is a stocks table using raw SQL in Laravel I don't know how to do it.

In MySQL, we can get it by using the below query

select b.name,sum(s.quantity)as Total from stocks s JOIN books b on s.book_id = b.id GROUP by b.name

any kind of help will be highly appreciated.

0 likes
2 replies
UsmanBasharmal's avatar
UsmanBasharmal
OP
Best Answer
Level 3

Thanks, I find it

    $com2 = DB::select('select b.name as bookname,sum(s.quantity)as Total from stocks s JOIN books b on 
    s.book_id = b.id GROUP by b.name');

    return response()->json( $com2);

Please or to participate in this conversation.