Posts Learn Components Snippets Categories Tags Tools About

Laravel Subquery Code Example

Code example for writing a subquery in Laravel using DB facade

Created on Nov 13, 2021


Imagine having RAW SQL like the following where you are explicitly selecting columns from a table and from within the table that you select itself has a subquery that selects another table with different conditions.
FROM `products` p 
WHERE `p`.`id` IN (
    FROM `product_category`
    WHERE `category_id` IN ('223', '15')
AND `p`.`active`=1
This RAW SQL query can easily be written in Laravel and to achieve this in Laravel you can make use of the DB facade. Here's an example of how you can convert the RAW SQL above into Laravel Fluent.

use \DB;

    ->whereIn('id', function($query) {
              ->whereRaw('orders.user_id =');

The above code will produce the following SQL code.
select * from users where id in (
    select 1 from orders where orders.user_id =
For more information do have a look at the advanced where clause documentation for Fluent.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Laravel Subquery Code Example


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours