Table of Contents
2. Subquery in FROM Clause (Subquery Joins)
3. Subquery in WHERE Clause
4. Subquery in ORDER BY Clause
Key Tips
Home PHP Framework Laravel How to use subqueries in Eloquent in Laravel?

How to use subqueries in Eloquent in Laravel?

Aug 05, 2025 am 07:53 AM
laravel eloquent

Laravel Eloquent supports subqueries in SELECT, FROM, WHERE, and ORDER BY clauses, enabling flexible data retrieval without raw SQL; 1. Use selectSub() to add computed columns like post count per user; 2. Use fromSub() or closure in from() to treat subquery as derived table for grouped data; 3. Use whereExists(), whereNotExists(), or scalar subqueries in where() for conditional filtering based on related data; 4. Pass subqueries directly to orderBy() to sort by values from related records, such as users ordered by latest post date; always prefer whereColumn() for column comparisons and consider performance impacts on large datasets by evaluating alternatives like joins or eager loading.

How to use subqueries in Eloquent in Laravel?

Using subqueries in Eloquent in Laravel allows you to embed one query inside another, which is useful when you need to filter, select, or order results based on data from related or the same tables. Laravel’s Eloquent ORM, built on top of the Query Builder, supports subqueries in SELECT, FROM, WHERE, and ORDER BY clauses starting from Laravel 5.6 .

How to use subqueries in Eloquent in Laravel?

Here’s how to use subqueries effectively in Eloquent:


1. Subquery in SELECT Clause

Use a subquery to add a calculated or aggregated column in your result.

How to use subqueries in Eloquent in Laravel?
use Illuminate\Database\Query\Expression;

$users = User::select('users.*', new Expression('(' . 
    Post::selectRaw('COUNT(*)')
        ->whereColumn('posts.user_id', 'users.id')
        ->toSql() 
    . ') as post_count'
))
->addBinding(Post::selectRaw('COUNT(*)')
    ->whereColumn('posts.user_id', 'users.id')
    ->getBindings(), 'select')
->get();

Or, better: use selectSub() for cleaner syntax:

$users = User::selectSub(
    Post::whereColumn('posts.user_id', 'users.id')->selectRaw('COUNT(*)'),
    'post_count'
)->get();

✅ This adds a post_count field to each user, counting their posts.

How to use subqueries in Eloquent in Laravel?

2. Subquery in FROM Clause (Subquery Joins)

Use a subquery as a derived table in the FROM clause.

$latestPosts = Post::select('user_id', DB::raw('MAX(created_at) as latest_post_date'))
    ->groupBy('user_id');

$users = User::fromSub($latestPosts, 'latest_posts')
    ->join('users', 'users.id', '=', 'latest_posts.user_id')
    ->get();

Alternatively, using from() with a closure:

$users = DB::table(function ($query) {
    $query->select('user_id', DB::raw('MAX(created_at) as last_post'))
          ->from('posts')
          ->groupBy('user_id');
}, 'latest_posts')
->join('users', 'users.id', '=', 'latest_posts.user_id')
->select('users.name', 'latest_posts.last_post')
->get();

✅ Useful when you need to work with grouped or filtered data as a base table.


3. Subquery in WHERE Clause

Use a subquery to compare values conditionally.

$users = User::where('id', '!=', function ($query) {
    $query->from('users')
          ->selectRaw('MAX(id)'); // Exclude the latest user
})->get();

More practical example: Get users whose latest post was over a month ago.

$users = User::whereExists(function ($query) {
    $query->select(DB::raw(1))
          ->from('posts')
          ->whereColumn('posts.user_id', 'users.id')
          ->where('posts.created_at', '>', now()->subMonth());
})->get();

Or use a scalar subquery:

$lastLoginThreshold = now()->subDays(30);

$inactiveUsers = User::where(function ($query) use ($lastLoginThreshold) {
    $query->where('last_login', '<', $lastLoginThreshold)
          ->orWhereNull('last_login');
})
->where('id', 'in', function ($q) {
    $q->select('user_id')
      ->from('posts')
      ->where('created_at', '>', now()->subYear());
})->get();

✅ Use whereExists, whereNotExists, or scalar comparisons for conditional filtering.


4. Subquery in ORDER BY Clause

Order results based on a value from a related table using a subquery.

Example: Order users by the creation date of their latest post.

$users = User::orderByDesc(
    Post::select('created_at')
        ->whereColumn('posts.user_id', 'users.id')
        ->latest()
        ->limit(1)
)->get();

Or more explicitly:

$users = User::select('users.*')
    ->orderByDesc(
        Post::whereColumn('posts.user_id', 'users.id')
            ->selectRaw('MAX(created_at)')
    )
    ->get();

✅ This avoids joining and grouping, and works well with indexes.


Key Tips

  • Always use whereColumn() when comparing columns between the main query and subquery.
  • Use selectSub() and fromSub() for cleaner, more readable code.
  • Be cautious with performance—subqueries can be slower on large datasets. Consider using joins or eager loading where appropriate.
  • When using raw subqueries, don’t forget to bind parameters manually if needed (though Laravel often handles this).

Basically, Laravel makes subqueries manageable and expressive. Whether you're selecting, filtering, or sorting based on related data, subqueries in Eloquent give you the flexibility without dropping down to raw SQL in most cases.

The above is the detailed content of How to use subqueries in Eloquent in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

How to use accessors and mutators in Eloquent in Laravel? How to use accessors and mutators in Eloquent in Laravel? Aug 02, 2025 am 08:32 AM

AccessorsandmutatorsinLaravel'sEloquentORMallowyoutoformatormanipulatemodelattributeswhenretrievingorsettingvalues.1.Useaccessorstocustomizeattributeretrieval,suchascapitalizingfirst_nameviagetFirstNameAttribute($value)returningucfirst($value).2.Usem

What are Repository Contracts in Laravel? What are Repository Contracts in Laravel? Aug 03, 2025 am 12:10 AM

The Repository pattern is a design pattern used to decouple business logic from data access logic. 1. It defines data access methods through interfaces (Contract); 2. The specific operations are implemented by the Repository class; 3. The controller uses the interface through dependency injection, and does not directly contact the data source; 4. Advantages include neat code, strong testability, easy maintenance and team collaboration; 5. Applicable to medium and large projects, small projects can use the model directly.

How to use subqueries in Eloquent in Laravel? How to use subqueries in Eloquent in Laravel? Aug 05, 2025 am 07:53 AM

LaravelEloquentsupportssubqueriesinSELECT,FROM,WHERE,andORDERBYclauses,enablingflexibledataretrievalwithoutrawSQL;1.UseselectSub()toaddcomputedcolumnslikepostcountperuser;2.UsefromSub()orclosureinfrom()totreatsubqueryasderivedtableforgroupeddata;3.Us

How to create a RESTful API with Laravel? How to create a RESTful API with Laravel? Aug 02, 2025 pm 12:31 PM

Create a Laravel project and configure the database environment; 2. Use Artisan to generate models, migrations and controllers; 3. Define API resource routing in api.php; 4. Implement the addition, deletion, modification and query methods in the controller and use request verification; 5. Install LaravelSanctum to implement API authentication and protect routes; 6. Unify JSON response format and handle errors; 7. Use Postman and other tools to test the API, and finally obtain a complete and extensible RESTfulAPI.

Laravel MVC: architecture limitations Laravel MVC: architecture limitations Aug 03, 2025 am 12:50 AM

Laravel'simplementationofMVChaslimitations:1)Controllersoftenhandlemorethanjustdecidingwhichmodelandviewtouse,leadingto'fat'controllers.2)Eloquentmodelscantakeontoomanyresponsibilitiesbeyonddatarepresentation.3)Viewsaretightlycoupledwithcontrollers,m

How to handle recurring payments with Laravel Cashier? How to handle recurring payments with Laravel Cashier? Aug 06, 2025 pm 01:38 PM

InstallLaravelCashierviaComposerandconfiguremigrationandBillabletrait.2.CreatesubscriptionplansinStripeDashboardandnoteplanIDs.3.CollectpaymentmethodusingStripeCheckoutandstoreitviasetupintent.4.SubscribeusertoaplanusingnewSubscription()anddefaultpay

Understanding MVC: How Laravel Implements the Model-View-Controller Pattern Understanding MVC: How Laravel Implements the Model-View-Controller Pattern Aug 02, 2025 am 01:04 AM

LaravelimplementstheMVCpatternbyusingModelsfordatamanagement,Controllersforbusinesslogic,andViewsforpresentation.1)ModelsinLaravelarepowerfulORMshandlingdataandrelationships.2)ControllersmanagetheflowbetweenModelsandViews.3)ViewsuseBladetemplatingfor

See all articles