Question

I have a search form in my Laravel app that searches through a list of properties. My properties table has a Model already, and is connected to another Model/table called details, which contains things like if a certain property has a garden, garage etc, through a one-to-many relationship. When doing index or show stuff this works fine - I can get the details for a property using $property->details.

The search form has a field where the user can search for such details, and this is where I'm struggling. I don't just need to find the detail itself, I need to first see if anything present in the input matches anything in the Details table, then see if the foreign key (called prop_id) matches any of my Property id's, then include those properties in the results. Something like:

    $query = Property::where('archived',0);

    $query->details->where('text',$keyword);

    $results = $query->get();

The reason this won't work is because details isn't a property of $query, but I'm not sure what to use as an alternative as calling Property::where() again would surely reset the whole query. I'm storing it all in a $query variable because all the fields in my form are optional, so I'm building the query based only on the inputs that have values in.

Bit stumped here, so if anyone has already tackled something like this, the tips would be appreciated. Cheers!

Was it helpful?

Solution

Use whereHas:

$query = Property::where('archived', 0)->whereHas('details', function ($q) use ($keyword)
{
    $q->where('text', $keyword);
});

$results = $query->get();

OTHER TIPS

You may try something like this:

$query = Property::where('archived', 0);
if(isset($keyword)) {
    $query->whereHas('details', function ($q) use ($keyword) {
        $q->where('text', $keyword);
    });
}
$results = $query->get();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top