Home > Software engineering >  How to order search results in Laravel
How to order search results in Laravel

Time:02-25

how can I order the results in a search field showing first the results that starts first with the letters the user is typing. My website currently shows the results like this: enter image description here

But i want to display the results like this, when the user types "mer" enter image description here

My current code is:

public $search = "";

public function render()

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

This is made with Laravel Thanks for your time

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