2

我正在使用 Laravel 开发一个 API,我希望能够使用该 API 进行搜索,但我无法做到这是我的方法

   public function searchapi()
   {

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

   /* $books = Book::when($search, function ($query, $search) {
       return $query->where('name', 'LIKE', "%{$search}%");
   })
    ->orderBy('created_at', 'desc')
    ->simplepaginate(12); */

  $books = Book::where('name', 'LIKE', "%{$search}%")->Paginate(16);
  $author = Author::where('name', 'LIKE', "%{$search}%")->Paginate(16);
  $genre = Category::where('title', 'LIKE', "%{$search}%")->Paginate(16);



   return Response::json(array(
    'books' => $books, 
    'author'=>$author,
    'genre'=>$genre,
 ));


}

我不知道我做错了什么,因为这会在使用邮递员搜索时返回数据库中的所有数据。

我在 api.php 中的路线

Route::get('/search', 'BooksController@searchapi');

更新

我正在使用邮递员进行测试。我通过Key=search并且value=searchterm

4

1 回答 1

1

方法:

public function searchapi(Request $request)
   {

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

   /* $books = Book::when($search, function ($query, $search) {
       return $query->where('name', 'LIKE', "%{$search}%");
   })
    ->orderBy('created_at', 'desc')
    ->simplepaginate(12); */

  $books = Book::where('name', 'LIKE', "%{$search}%")->Paginate(16);
  $author = Author::where('name', 'LIKE', "%{$search}%")->Paginate(16);
  $genre = Category::where('title', 'LIKE', "%{$search}%")->Paginate(16);



   return Response::json(array(
    'books' => $books, 
    'author'=>$author,
    'genre'=>$genre,
 ));


}

路线:

Route::post('/search', 'BooksController@searchapi');
于 2019-12-11T09:33:43.923 回答