Model of Category
public function lists(){
return $this->belongsToMany(Listing::class);
}
Model of Listing
public function categories(){
return $this->belongsToMany(Category::class)
->withPivot(['category_id','listing_id']);
}
Controller: when I dd
this query then I get all lists that is in listings table but I just want to get those lists whose have these categories.
if($request->categories){
$var = $request->categories; // data in array 1,2,3
$lists = Listing::with(['categories' => function ($query) use($var) {
$query->whereIn('category_id',$var);
}])->get();
dd($lists);
CodePudding user response:
This code is working perfect
$state=$request->state;
$type=$request->type;
$categories=$request->categories;
if(!$request->all()==null){
$lists = Listing::when($state!=Null,function ($query) use ($state) {
return $query->where('state', $state);})->
when($type!=Null,function ($query) use ($type) {
return $query->where('type', $type);});
if(!$categories==null){
foreach($categories as $var){
$lists->whereHas('categories',function($q) use($var){
$q->where('category_id',$var);
});
}
}
$lists=$lists->get();
}
CodePudding user response:
Give some id name to your table
<table id="userTable" style="display: table;" class="table table-responsive text-center table-striped table-hover">
and then use the following script:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#userTable').DataTable( {
scrollY: "400px",
scrollX: true,
scrollCollapse: true,
paging: true,
columnDefs: [ {
sortable: false,
"class": "index",
targets: 0
} ],
order: [[ 4, 'dsc' ]],
fixedColumns: true
} );
table.on( 'order.dt search.dt', function () {
table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i 1;
} );
} ).draw();
} );
</script>
now you must able to search, filter, reorder your table.