Home / Snippets / Laravel Subquery Code Example
Laravel Subquery Code Example cover

Laravel Subquery Code Example

173

3 years ago

0 comments

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.
SELECT 
    `p`.`id`,
    `p`.`name`, 
    `p`.`img`, 
    `p`.`safe_name`, 
    `p`.`sku`, 
    `p`.`productstatusid` 
FROM `products` p 
WHERE `p`.`id` IN (
    SELECT 
        `product_id` 
    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.
<?php

use \DB;

DB::table('users')
    ->whereIn('id', function($query) {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this