Laravel 5.3 API中的搜索功能

时间:2017-01-14 05:30:16

标签: php laravel api search laravel-5.3

我正在为front end and mobile apps实施API,现在我正在search function工作,用户可以在其中输入column name或任何data我应该能够以JSON格式提供他们请求的数据

我真的不知道如何根据他们输入的数据进行查询,所以我这样做了

在我的控制器中

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
    ]);
}

我的模特是

<?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'];
}

和我的路线

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
});

,参数可能是

   http://localhost:8000/api/v1/search?data=name(maybe any column data from above model)
你可以告诉我或者给我一些例子如何query and return as json

谢谢

1 个答案:

答案 0 :(得分:3)

您可以为需要搜索的每个字段链接where

$data = $request->get('data');

$drivers = Driver::where('first_name', 'like', "%{$data}%"))
                 ->orWhere('last_name', 'like', "%{$data}%"))
                 ->get();

return Response::json([
    'data' => $drivers
]);

如果需要,您可以添加更多where子句。