Search code examples
laravellumen

How to create api for search in lumen/laravel?


How to create api for search in lumen/laravel .. I tried using keyword but not working.

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

}

Solution

  • You should change this line :

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

    Also i think You should the pagination within the model query, not on the returned result.