Laravel Eloquent Select CASE?
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: Injecting CASE Statements into Laravel Eloquent Queries: A Comprehensive Guide
Body:
Laravel is a powerful framework that allows developers to create efficient and scalable applications. One of its key features is the use of Eloquent, an active record pattern implementation for querying databases using PHP. However, occasionally you may face situations where you want to incorporate CASE statements in your queries. This blog post aims to provide a comprehensive guide on how to achieve that.
What is a CASE Statement?
A CASE statement is a construct used in SQL queries to evaluate multiple conditions and return different results based on the evaluation outcome. It operates like an if-else statement, making your query more dynamic and specific.Implementing CASE Statements within Laravel Eloquent Queries
In Laravel Eloquent, you can use the raw() method to execute custom SQL statements. In this case, we can write our CASE statement as a part of your query and call it by using that method. This is done because the raw query cannot be processed automatically by Eloquent's magic methods.Example Code
Here's an example code demonstrating how to inject a CASE statement into a Laravel Eloquent query:$shares = Share::where('shares.status', '=', SHARE_STATUS_APPROVED)
->where('shares.deleted', '=', '0')
->where('locations.lat', '<=', $nelat)
->where('locations.lat', '>=', $swlat)
->where('locations.lng', '>=', $nelng)
->where('locations.lng', '<=', $swlng)
->where('users.id', '=', $user)
->orWhere('shares.connected_user_id', '=', $user)
->join('users', 'shares.user_id', '=', 'users.id')
->join('locations', 'locations.id', '=', 'users.location_id')
->join('provinces', 'provinces.id', '=', 'locations.province_id')
->join('countries', 'countries.id', '=', 'locations.country_id')
->select(...) // Your existing query selects
->raw('(CASE WHEN users.id = '. $user .' THEN 1 ELSE 0 END) AS is_user')
->orderBy('shares.created_at', 'desc')
->orderBy('users.id', 'asc')
->orderBy('shares.connected_user_id', 'asc')
->get();
From this example, we can see that the CASE statement is called using the raw() method. It's crucial to remember to use the correct syntax for your specific case (no pun intended).