Home > Mobile >  Sort 'search results' based on the position of the 'search term' in them
Sort 'search results' based on the position of the 'search term' in them

Time:03-02

I want to order the results showing those that start with the letters the user is typing first.

public $search = "";

public function render()
{
    $business = Empresa::where("name", "like", "%" . $this->search . "%")
        ->orderBy("name")
        ->take(5)
        ->get();
    return view('livewire.general.simpleSearch', compact("business"));
}

My website currently shows the results like this:

enter image description here


Instead, when the user types mer I want to display the results like this:

enter image description here

CodePudding user response:

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

        $business = Empresa::where("name", "like", "%$search%")
            ->get();

        $sorted = $business->sortBy(function ($result) use ($search) {
            return strpos($result->name, $search);
        })->take(5);

        return view('livewire.general.simpleSearch')
            ->with('business', $sorted->values()->all());
    }

CodePudding user response:

You try this Empresa::where("name", "like", $this->search . "%")->take(5)->get();

CodePudding user response:

You should not put % before your query

$business = Empresa::where("name", "LIKE", $this->search . "%")->orderBy("name")->take(5)->get();

In sql when using LIKE query % act as wildcard. If you put % before your search string it will search ending with your string, if you put % after your search string it will search starting with your string. Since you put % before and after your search string it will search every row contains your search query.

  • Related