When displaying a menu of categories and products for an authenticated user, I encountered a problem with the search bar. Despite wanting only certain categories/products to be displayed, the search bar was fetching products from all categories. To address this issue, I attempted to send a variable containing a list of category objects via an ajax request:
Illuminate\Database\Eloquent\Collection {#1381 ▼
#items: array:1 [▼
0 => App\Models\Categorie {#1385 ▶}
]
}
However, I faced an error with the $categories variable in my ajax script. I was unsure how to utilize this variable in my script to filter search results based on specific categories. Here is the script I attempted:
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
var data =[];
$.each({{$categories}} , function( index, value ) {
data.push(value->id);
});
console.log(data);
$.ajax({
url:"{{ route('search') }}",
method:'GET',
data: {query: query, data:data },
dataType:'json',
success: function(data) {
if (data.success) {
$('#result').html(data.html);
} else {
console.log(data.message);
}
}
})
}
$(document).on('keyup', '#keyword', function($e){ // define event parameter
var query = $(this).val();
fetch_customer_data(query);
$e.preventDefault();
});
});
Here is the controller method:
public function search(Request $request)
{
try{
if($request->ajax()) {
$query = $request->get('query');
if(empty($query)) {
return back()->withError("Désolé, une erreur de serveur s'est produite (requête vide)");
}
else {
$products =DB::table('product_categories')
->join('produits', 'product_categories.produit', '=', 'produits.id')
->join('categories', 'product_categories.categorie', '=', 'categories.id')
->select('produits.*')
->whereIn('product_categories.categorie',$request->data)
->where([['nomProduit','LIKE','%'.$query.'%'],['categories.visibilite','=',1],['produits.visibilite','=',1]])
->orWhere([['typeActivite','LIKE','%'.$query.'%'],['categories.visibilite','=',1],['produits.visibilite','=',1]])
->get();
}
$total = $products->count();
$html = view('front.search_result', [
'products' => $products,
])->render();
return response()->json([
'success' => true,
'html' => $html,
'total' => $total,
], 200);
} else {
return response()->json([
'success' => false,
'message' => "Oups! quelque chose s'est mal passé !",
], 403);
}
}catch (Exception $e) {
Alert::error('Erreur ', $e->getMessage())->autoClose(false);
return redirect()->back();
}catch (Error $e) {
Alert::error('Erreur ', $e->getMessage())->autoClose(false);
return redirect()->back();
}
}
Here is the structure of the variable $categories:
Illuminate\Database\Eloquent\Collection {#1381 ▼
#items: array:1 [▼
0 => App\Models\Categorie {#1385 ▼
#fillable: array:4 [▶]
#files: array:1 [▶]
#connection: "mysql"
#table: "categories"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 4
"parent_id" => null
"categorie" => "Informatique"
"description" => "informatique"
"photo" => "categories/Informatique .jpg"
"visibilite" => 1
"deleted_at" => null
"created_at" => "2021-04-19 06:33:16"
"updated_at" => "2021-08-07 14:06:45"
]
#original: array:9 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
Finally, here is the error I encountered: https://i.sstatic.net/if52h.png