I want to skip some json key if the value of this key is not filled. Because if it's not filled, it returns my bad result.
Check out my code on the backend and front-end.
Backend Laravel:
public function searchFilterCar(Request $request, Car $car)
{
if ($request->has('car_type')) {
$car = $car->where('car_type', $request->input('car_type'))->with('images');
}
if ($request->has('mark')) {
$car = $car->where('mark', $request->input('mark'))->with('images');
}
if ($request->has('model')) {
$car = $car->where('model', $request->input('model'))->with('images');
}
if ($request->has('fuel')) {
$car = $car->where('fuel', $request->input('fuel'))->with('images');
}
if ($request->has('circuit')) {
$car = $car->where('circuit', $request->input('circuit'))->with('images');
}
return response()->json($car->get());
}
Frontend Vue:
async searchCar(){
this.loading = true;
try {
let response = await axios.post('car/filtersearch', {
car_type: this.selectedCarType,
mark: this.selectedCarObject.name,
model: this.selectedModel,
fuel: this.selectedFuel,
circuit: this.selectedCircuit
});
console.log(response);
this.cars = response.data;
} catch (err) {
console.log(err)
}
},
Look at my payload. https://imgur.com/tl3yelP I do not know if the solution is on the front or on the back? At the moment, I think it's easiest if an empty value does not send an absolutely json with that key and values than just skipping them. Maybe the backend could be a correction but I think it's easier on the front? Help?
You need to use filled
instead of has
if you want to check if a value is present on the request and is not empty.
......
if ($request->filled('fuel')) {
$car = $car->where('fuel', $request->input('fuel'))->with('images');
}
......
See: https://laravel.com/docs/5.8/requests - Section: Determining If An Input Value Is Present