Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eas3011's avatar

Search in three related table

Hi

I have 3 tables: Visitors (ID, name, places_id, ...) Places (Id, name, country_id ...) and Countries (Id, Name, ...).

Visitors is related to Places in a Model. Places is related to Countries in another Model.

I need to do a single search for a keyword in the three tables and return the result in one table.

Thank you for helping.

0 likes
2 replies
SilenceBringer's avatar
Level 55

@eas3011 assuming you have defined place relation on your Visitor model, and country relation on your Place model

$search = 'keyword';

$visitors = Visitor::where('name', 'like', '%' . $search . '%')
    ->orWhereHas('place', function ($placeQuery) use ($search) {
        $placeQuery->where('name', 'like', '%' .. $search . '%')
            ->orWhereHas('country', function ($countryQuery) use ($search) {
                $countryQuery->where('name', 'like', '%' .. $search . '%');
            });
    })
    ->with('place.country')
    ->get();
1 like

Please or to participate in this conversation.