Reputation: 183
I'm studying keyword search. I successed single keyword search and now I'm trying to make multiple one.
as Half-width space keyword split. I use this Middlewarefrom this website
https://qiita.com/logue/items/64c4b5545f76ef17de70
When I dd() . I can see keyword split are good. but when I search function runs There is no sql sentence appear and I can display empty result page.
Could you teach me correct code please?
Controller
public function order_adv()
{
$keyword = request('search_adv');
if(!empty($keywords)) {
foreach ($keywords as $keyword) {
$products = Product::when('w_m','like','%'.$keyword.'%');
}
}
return view('products.result_adv' , compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
WEB.php
Route::get('products/search_adv', [ProductController::class, 'search_adv'])->name('search_adv');
Route::post('products/search_adv', [ProductController::class, 'order_adv'])->name('products.search_adv')->middleware('keyword');
Upvotes: 1
Views: 154
Reputation: 15319
You can use where call back method
public function order_adv()
{
$keywords =explode(' ',request('search_adv'));
$products = Product::when(count((array)$keywords),function($query)use($keywords){
$query->where(function($query)use($keywords){
foreach ($keywords as $keyword) {
$query->orWhere('w_m','like','%'.$keyword.'%');
}
});
})->get();
return view('products.result_adv' , compact('products'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
Upvotes: 1
Reputation: 831
$keywords = request('search_adv');
if (count($keywords) > 0) {
$products = Product::where(function($query)use($keywords) {
foreach ($keywords as $keyword) {
$query->orWhere('w_m', 'LIKE', "%{$keyword}%");
}
})->get();
}
In your case use where Clauses, https://laravel.com/docs/8.x/queries#where-clauses
use when in condition statement, https://laravel.com/docs/8.x/collections#method-when
Upvotes: 1