I'm a bit starter in the Laravel system so please bear with me.
Currently I have stored images in the database and they have columns featured and approved. They both have status 0, and 1. Approved/Not approved.
What I'm trying to to is to be able to filter from the admin dashboard:
- All images ( this will be all images no mater what status they have - 0 and 1
- Only approved - status 1
- Not approved - status 0
This is what I have in my index.blade.php
<div class="col-md-2">
<div class="form-group">
<label for="featured">Featured</label>
<select class="form-control" name="featured" id="featured">
<option value=""> All</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="form-group">
<label for="approved">Approved</label>
<select class="form-control" name="approved" id="approved">
<option value=""> All</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Search</button>
And this is the query that I'm trying to build in the controller
public function index(Request $request)
{
$approved = $request->approved;
$featured = $request->featured;
$images = Images::when($approved, function($query, $approved) {
if ($approved == '0') {
return $query->where('approved', 0);
} else if ($approved == '1' ){
return $query->where('approved', 1);
} else {
return $query->where('approved', [0,1]);
}
})
->when($featured, function($query, $featured) {
if ($featured == '0') {
return $query->where('featured', 0);
} else if ($featured == '1' ){
return $query->where('featured', 1);
} else {
return $query->where('featured', [0,1]);
}
})
->latest()->get();
return view( .... );
}
This is what I have in route
Route::resource('images', 'ImagesController')->except('show');
First problem is that when I choose option "All" it doesn't show anything, and when I choose "No" or "Yes" it shows same results.
I also don't think that this is the correct way of building such query.
dd($approved)I've got result"1","0"or""if I chooseAll