Support the ongoing development of Laravel.io →
Database Eloquent

Hello,

I am trying to get a list of all unassigned addresses to be displayed in a combo-box for the end-user to pick via AJAX. For now I have two Models: Location and Address with the relationship of one to one.

For now I am achieving the desired result with the following function:

public function getUnassignedAddresses()
    {
        $addresses = Address::select(['id', 'name'])->get();
        $unassigned = [];

        foreach ($addresses as $address) {
            if (!is_object($address->location))
            {
                $unassigned[] = $address;
            }
        }

        return response()->json($unassigned);
    }

Now my question is how could I do this better. Like doing it without a foreach? Is there any way to use something like a where before the get() ? so that I can use less queries? The queries that are ran now by the code are:

string 'select `id`, `name` from `addresses`' (length=36)
string 'select * from `locations` where `locations`.`address_id` = ? and `locations`.`address_id` is not null limit 1' (length=109)

where the second query is executed (repeated) for every address I have in DB. You can see where this could lead right?

Thank you in advance for your time.

Last updated 3 years ago.
0

On the phone so YMMV:

$addresses = Address::has('location', '=', 0)->get();
0

Of course. Thank you for this quick and simple solution.

Here is more info from the official docs:

http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

0

Sign in to participate in this thread!

Eventy

Your banner here too?

uibar uibar Joined 20 Mar 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.