如何为 lumen/laravel 中的搜索创建 api?

How to create api for search in lumen/laravel?

如何创建 api 以在 lumen/laravel 中进行搜索..我尝试使用关键字但不起作用。

public function index(){

    $Employees  = Employees::all();
    $page = Input::get('page', 1); 

    $keyword = Input::get('keyword', '');

    if ($keyword!='') {
         $keyword = Employees::
                where("firstname", "LIKE","%$keyword%")
                ->orWhere("lastname", "LIKE", "%$keyword%");           
        }


    $itemPerPage=5;

    $count  = Employees::count();

    $offSet = ($page * $itemPerPage) - $itemPerPage;

    $itemsForCurrentPage = array_slice($Employees->toArray(), $offSet, $itemPerPage);

   return new LengthAwarePaginator($itemsForCurrentPage, count($Employees), $itemPerPage, $page,$keyword);

}

您应该更改此行:

if ($keyword!='') {
     $Employees  = Employees::
            where("firstname", "LIKE","%$keyword%")
            ->orWhere("lastname", "LIKE", "%$keyword%")
            ->get();           
}

另外我认为你应该在模型查询中分页,而不是在返回的结果中。

你也可以这样做 在你的模型中创建的范围内定义你的逻辑并在你的controller.here中使用它是我的意思

这应该在您的模型中

public function scopeFilter($query, $params)
{

    if ( isset($params['name']) && trim($params['name'] !== '') ) 
    {
        $query->where('name', 'LIKE', trim($params['name']) . '%');
    }

   if ( isset($params['state']) && trim($params['state'] !== '') ) 
    {
        $query->where('state', 'LIKE', trim($params['state']) . '%');
    }

    return $query;
}

在你的控制器中有类似

的东西
public function filter_property(Request $request)
{
    $params = $request->except('_token');
    $product = Product::filter($params)->get();
    return response($product);
}

您可以通过阅读范围 laravel 文档和此博客 post here

获得更多信息