How to Create a Simple search in your website use Laravel?
1 min readJul 23, 2021
- First, for example, if you own an online store and there is a table of
Categories
and you want to do a search for anyCategory
.
- In the CategoriesController file in the
Categories
: - add the function search in CategoriesController
- In the example, we are searching in the name column from the
categories
table.
public function search_category(Request $request){
// Get the search value
$search = $request->input('search');
// Search in the name column from the categories table
$categories = Category::query()
->where('name', 'LIKE', "%{$search}%")
->get();
// Return the resluts
return view('search', compact('categories'));
}
- Now: Don’t forget to add the route for the Search function
Route::get('/search/', 'CategoriesController@search_category')->name('search');
- To complete this, you must create a view and create a form search
<form action="{{ route('search') }}" method="GET">
<input type="text" name="search" required/>
<button type="submit">Search</button>
</form>
- Now to display the results
@if($categories->isNotEmpty())
@foreach ($categoriesas $category)
<ol>
<li>{{ $categories->name}}</li>
</ol>
@endforeach
@else
<div>
<h2>No categories :( </h2>
</div>
@endif
- Above, we have displayed the search result, and in the event that there is no similar category to the one we searched for, the phrase “
No categories :(
” will be displayed
There are advanced ways to search and this is just one of many ways