Laravel在搜索响应中发送API JSON

时间:2018-09-18 08:45:12

标签: json laravel response

我有一个搜索字段来过滤新闻,但是我不知道这是正确的方法。

<form method="GET" action="search" class="form-inline my-2 my-lg-0">
  <input style="width:430px;" class="form-control py-2" type="search" name="search" value="Buscar Noticia" id="buscar" onclick='javascript: this.value = ""'>
  <span class="input-group-append">
  <button class="btn btn-outline-secondary" type="submit">
    <i class="fa fa-search"></i>
  </button>
  </span>

这是我的NoticiaResource:

public function toArray($request)
{
    $filtro = $request->get('search');

    if(!empty($filtro))
    {
        $noticias = Noticia::where('titulo', 'LIKE', '%' .$filtro . '%')->paginate(4);   
    } 
    else
    {
        $noticias = Noticia::all();    
    }

    return $noticias->toArray();
} 

NoticiasController:

public function show(Noticia $noticias)
{
    NoticiaResource::withoutWrapping();
    return new NoticiaResource($noticias);
}

在api.php中添加api路由:

Route::get('noticias', 'NoticiasController@show');

并路由返回web.php中的相同网址:

Route::get('search', function(Request $request){
    return redirect('noticias.html');
})->name('search');

问题是JSON总是返回所有新闻,不过滤任何内容。

1 个答案:

答案 0 :(得分:0)

尝试public function toArray(Request $request) Docs