Eloquent Advanced Subqueries


Eloquent also offers advanced subquery support, which allows you to pull information from related tables in a single query. For example, let’s imagine that we have a table of flight destinations and a table of flights to destinations. The flights table contains an arrived_at a column which indicates when the flight arrived at the destination.

Using the subquery functionality available to the select and addSelect methods, we can select all of the destinations and the name of the flight that most recently arrived at that destination using a single query:

use App\Destination;
use App\Flight;

return Destination::addSelect(['last_flight' => Flight::select('name')
    ->whereColumn('destination_id', 'destinations.id')
    ->orderBy('arrived_at', 'desc')

Subquery Ordering

In addition, the query builder’s orderBy the function supports subqueries. We may use this functionality to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single query against the database:

return Destination::orderByDesc(
        ->whereColumn('destination_id', 'destinations.id')
        ->orderBy('arrived_at', 'desc')


More Posts

Mombasa Web Development

We are a Mombasa website design company, digital marketing agency, social media, and PR agency in one super-creative blender. Digital Marketing Kenya brand tenders and

Limited Google My Business functionality due to COVID-19

During the unprecedented COVID-19 situation, we are taking steps to protect the health of our team members and reduce the need for people to come into our offices. As a result, there may be some temporary limitations and delays in support as we prioritize critical services.


How to Make Money in Forex Trading

Ever heard of forex trading? What comes to your mind when you hear of it? Forex trading is a good platform to for making a good return for your money with less hustles and little commitment of your time. Choosing the brokerage to trade with is one of the key issues to consider when selecting the brokerage to start trading with

Send Us A Message