So I have a search function, and based on the results I want to show different views, or redirect, etc. Right now I am doing the following:
public function search()
{
$results = Event::where('name', 'LIKE', "%{$this->search}%")->get();
if ($results)
{
if ($results->count() > 1)
{
// return an index view with all search results
}
// There was only one result so we grab the result and redirect to the show view
$result = Event::where('name', 'LIKE', "%{$this->search}%")->first();
return redirect()->route(__('events.show'), [$result->slug]);
}
// No results
}
And yes although this does work, I would like to know if there is a way to get the same result without having to do multiple queries like I am doing now. Is it possible to achieve this with only one query? I do not wish to loop through the collection that I get from the initial ->get()
results though.
I am aware I could do a firstOr
or a firstOrFail
for example, but I do not wish to redirect upon the first
result, I still want to check if there is more than one result, and if so, to display all those results.
CodePudding user response:
get()
returns a collection. You could just do first()
or get(0)
on the Collection itself to return the first result.
$results = Event::where('name', 'LIKE', "%{$this->search}%")->get();
if ($results->isNotEmpty()) {
return $results->count() === 1
? view('show', ['event' => $results->first()])
: view('index', ['results' => $results]);
}
return view('no-results');