A search field is a useful function for users to find the information they need. To make a search field toward a web app in Laravel, their are few steps to go:
1. Make a route to the search function.
Firstly, we need to add a route to the search function in the route file (routes/web.php
).
Route::post('/products/search', 'ProductController@search')->name('products.search');
This means the URI is /products/search
with http method ‘post’ and route the request to the ‘search’ method in the ‘Product’ controller. The route name is ‘products.search’.
2. Make the search method in the controller.
The ‘search’ method in the ‘Product’ controller should be looked like this:
- Single keyword
If we have only one keyword, it is much simpler to deal with than the multiple one situation.
public function search(Request $request)
{
$request->validate([
'keyword' => 'required'
]);
$keyword = $request->get('keyword');
//single keyword search - start
$products = Product::where('prod_name', 'like', '%'.$keyword.'%')
orWhere('prod_desc', 'like', '%'.$keyword.'%')->get();
$products = Product::paginate(5);
// single keyword search - end
return view('products.index', compact('products'));
}
- Multiple keywords
What if we have more than one keywords? If so we need to change the ‘single keyword search’ of the code to the following:
$keywords = explode(' ', $request->get('keyword'));
$where = '';
foreach ($keywords as $id => $word) {
if ($id <> 0)
$where = $where.'or ';
}
$where = $where."prod_name like '%{$word}%' or prod_desc like '%{$word}%'";
}
$sql = "$where ORDER BY 'prod_id' DESC";
$products = Product::whereRaw($sql)->get();
3. Make a search field in the menu bar of the index view file.
Lastly, we need to add the following code to the index file in order to show the search box in the main menu bar. The file is
resources/views/products/layout.blade.php
in this example.
<form method="post" action="{{ route('products.search') }}" class="form-inline my-2 my-lg-0">
@csrf
<input class="form-control mr-sm-2" type="text" placeholder="Search"
aria-label="Search" name="keyword">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
As usual, a submit form tag is added with http post method. The action to {{ route('products.search' }}
is the blade template function to route to the route named ‘products.search’.
No comments:
Post a Comment