Krunal
Krunal

Reputation: 938

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

}

Upvotes: 0

Views: 1693

Answers (2)

Slycreator
Slycreator

Reputation: 1230

you can also do this define your logic in a scope created in you model and consume it in your controller.here is what i mean

This should be in your model

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

and in your controller have something like

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

you can get more by reading scope on laravel doc and this blog post here

Upvotes: 0

Bara' ayyash
Bara' ayyash

Reputation: 1925

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.

Upvotes: 1

Related Questions