I have a View to display a menu of categories and its products based on the authenticated user, which means I only want certain categories/products displayed, my problem is in the search bar when I type all products show from all categories but I want the search to only find products in those certain categories. That's why I tried to send with the ajax request a variable that contains a list of objects, these objects are my categories:
Illuminate\Database\Eloquent\Collection {#1381 ▼
#items: array:1 [▼
0 => App\Models\Categorie {#1385 ▶}
]
}
the problem is that ajax is giving me an error with my $categories variable, i don't know how to use this variable in my script i want to send the objects or a list of the object ids so i cant treat them in my controller using the WhereIn methode in my sql search request , here is my script :
<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);
//$('#result').html(data.html); remove this line
$e.preventDefault();
});
});
and here is my controller methode :
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) {
// Something else happened, completely unrelated to Stripe
Alert::error('Erreur ', $e->getMessage())->autoClose(false);
return redirect()->back();
}catch (Error $e) {
// Something else happened, completely unrelated to Stripe
Alert::error('Erreur ', $e->getMessage())->autoClose(false);
return redirect()->back();
}
}
and the type of the variable $categories is :
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 [▶]
}
] }
and finally here is the error :
CodePudding user response:
You probably need to {! json_encode($categories) !}
CodePudding user response:
Got it ! here is how it worked for me :
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
var data =[];
var cats = @json($categories->toArray());
console.log(cats);
$.each(cats , function( index, value ) {
data.push(cats[index].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);
//$('#result').html(data.html); remove this line
$e.preventDefault();
});
});
and didn't change nothing in my contorller i sent the $categories using compact