Laravel 5.3 API 中的搜索功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41647092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.3 Search function in API
提问by Mr Robot
I'm implementing an API for front end and mobile apps
now i'm working on search function
where a user may type column name
or any data
i should be able to provide the data they request in a JSON format
我现在正在实现一个 APIfront end and mobile apps
我正在研究search function
用户可以在何处输入column name
或任何data
我应该能够以 JSON 格式提供他们请求的数据
i really don't know how to query based on the data they input, so for i did this
我真的不知道如何根据他们输入的数据进行查询,所以我这样做了
in my controller
在我的控制器中
public function getSearchResults(Request $request) {
$search_drivers = Driver::all();
return Response::json([
'data' => $search_drivers->all() // i know this is not cool, i need to query based on the input data
]);
}
my model is
我的模型是
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Driver extends Model
{
use SoftDeletes;
protected $fillable = [
'agent_id',
'registration_center',
'registration_date',
'sponsor_name',
'event_name',
'registration_id',
'profile_photo',
'first_name',
'last_name',
'role',
'date_of_birth',
'marital_status',
'phone_number',
'alternate_phone_number',
];
protected $dates = ['deleted_at'];
}
and in my routes
在我的路线中
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function() {
Route::get('user', function (Request $request) {
return $request->user();
});
Route::resource('drivers', 'DriversController');
Route::resource('search', 'DriversController@getSearchResults'); //search route
});
and the parameters meight be
参数可能是
http://localhost:8000/api/v1/search?data=name(maybe any column data from above model)
could you please tell me or give me some example how to query and return as json
你能告诉我或者给我一些例子如何 query and return as json
Thank You
谢谢你
回答by Amit Gupta
You can chain where
for each field you need to search as:
您可以where
将需要搜索的每个字段链接为:
$data = $request->get('data');
$drivers = Driver::where('first_name', 'like', "%{$data}%"))
->orWhere('last_name', 'like', "%{$data}%"))
->get();
return Response::json([
'data' => $drivers
]);
You can add more where
clauses if you want.
where
如果需要,您可以添加更多子句。