Home > Blockchain >  Where clauses and search
Where clauses and search

Time:02-16

I'm new in Laravel and Livewire. I have problem with my code, I'm trying to use where clauses and search in one query. I have code like this.

This is in my controller

public function read()
{
    return Groom::query()
        ->search($this->search)
        ->orderBy($this->sortBy, $this->sortDirection)
        ->paginate($this->perPage);
}

and this one in my model

public function scopeSearch($query, $val)
{
    return $query
        ->where('status', '<>', 'selesai')
        ->leftJoin('pets', 'pets.id', '=', 'grooms.pet_id')
        ->where('name', 'like', '%' .$val. '%')
        ->where(function ($query) use ($val) {
            $query
                ->Orwhere('service', 'like', '%'. $val. '%')
                ->Orwhere('address', 'like', '%' .$val. '%')
                ->Orwhere('status', 'like', '%' .$val. '%');
        });
}

There's no error there, but my search isn't working

CodePudding user response:

Your generated SQL query is

select * from grooms
left join "pets" on "pets"."id" = "grooms"."pet_id"
where "status" <> 'selesai'
and "name" like ? and (
    "service" like ?
    or "address" like ?
    or "status" like ?
)
order by ...

Perhaps you want the name filter to be inside that grouped where? Try

public function scopeSearch($query, $val)
{
    return $query
        ->where('status', '<>', 'selesai')
        ->leftJoin('pets', 'pets.id', '=', 'grooms.pet_id')
        ->where(function ($query) use ($val) {
            $query
                ->orWhere('name', 'like', '%' .$val. '%')
                ->orwhere('service', 'like', '%'. $val. '%')
                ->orwhere('address', 'like', '%' .$val. '%')
                ->orwhere('status', 'like', '%' .$val. '%');
        });
}
  • Related