Search code examples
laraveleloquentlaravel-7

laravel filter to search name [space] surname together fails, individual name or surname search works


Looking for help fixing my search filter, currently it works fine when searching an individual name or surname but fails when searching combined name and surname (with a space between words). I feel like I'm pretty close to getting this to work as I'd like but just can't get it right. Any help would be greatly appreciated.

my model:

public function scopeSearchFilter($query, array $filters) {
        $searchTerm = $filters[0];
        $category = $filters[1];

        $query->when($filters[0] ?? false, fn($query, $searchTerm) =>
            $query->whereHas('author', fn ($query) =>
                $query->where('name', 'like', '%' . $searchTerm . '%')
                ->orWhere('surname', 'like', '%' . $searchTerm . '%')
            )
        );
}

my controller(using livewire btw):

    public $search;
    public $category;
   
    public function render()
    {   
        $search = $this->search;
        $category = $this->category;

        $posters = Poster::searchFilter([$this->search, $this->category])->paginate(10);
            
        return view('livewire.poster-data', [
            'posters' => $posters,
        ]);
        
    }
}

Solution

  • The way to approach this is by using DB facade, in order to concat the name and surname and then compare it with the value. If I were you I would do something like this :

    use Illuminate\Support\Facades\DB;
    
    
    public function scopeSearchFilter($query, array $filters) {
            $searchTerm = $filters[0];
            $category = $filters[1];
    
            $query->when($filters[0] ?? false, fn($query, $searchTerm) =>
                $query->whereHas('author', fn ($query) =>
                    $query->where('name', 'like', '%' . $searchTerm . '%')
                         ->orWhere('surname', 'like', '%' . $searchTerm . '%')
                         ->orWhere(DB::raw("CONCAT(`name`,' ',`surname`)"), 'like', '%' . $searchTerm . '%')
                    );
                );
    }