Home > Software design >  laravel filter to search name [space] surname together fails, individual name or surname search work
laravel filter to search name [space] surname together fails, individual name or surname search work

Time:11-02

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,
        ]);
        
    }
}

CodePudding user response:

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 . '%')
                );
            );
}

CodePudding user response:

Let's use John Doe as an example.

$searchTerm name surname
John X -
Doe - X
John Doe - -

Because you've split the name and surname in the database you'll need to either combine it again or split your $searchTerm too.

  • Related