我正在laravel 5.6中构建搜索功能 我有多个表单字段。搜索查询一切都很好。 在没有空数据的情况下,它从db返回所有数据。 我想检查至少一个字段是否不为空以通过查询,否则我想返回错误。我如何在Laravel中做到这一点。预先感谢
if ($request->all() != '') {
// Search for nursery based on their freeword.
if (!empty($request->input('description'))) {
$nursery->Where('description', 'LIKE', '%' . $request->input('description') . '%');
$nursery->orWhere('name', 'LIKE', '%' . $request->input('description') . '%');
}
答案 0 :(得分:0)
这将验证您所需的输入并给出错误(如果缺少),否则将进行搜索
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
public function search(Request $request){
$validator = Validator::make($request->all(), [
'locations' => 'required',
'price'=>'required',
'age'=>'required',
'description'=>'required'
]
);
if ($validator->fails()) {
$response=array('status'=>'error','errors'=>implode(',', $validator->errors()->all()));
return response()->json($response, 400);
}else{
// your code here ...
$nursery->Where('description', 'LIKE', '%' . $request->input('description') . '%');
$nursery->orWhere('name', 'LIKE', '%' . $request->input('description') . '%');
// your code here ...
return response()->json(['status'=>'success','result'=>$result],200);
}
}
答案 1 :(得分:0)
validation
方法$request->has('key')
方法或empty($request->all())
函数进行检查。$value = $request->input('key', 'default value');
检查值或将默认值设置为变量。when
方法请参阅示例:
$categoryId = $request->input('category_id', null);
$query = Product::query();
$query->when($categoryId, function ($q) use ($categoryId) {
return $q->where('category_id', $categoryId);
});
$query->get();