使用Laravel Scout搜索结果分页

时间:2019-01-21 16:09:24

标签: php laravel search pagination

我在使用Laravel ScoutTNTSearch driver进行分页时遇到问题。例如,我要搜索关键字“产品80”。 URL是localhost/search?keyword=product+80,当我转到下一页时,URL变成localhost/search?query=Product%2080&page=2.,它在搜索结果中不显示任何内容。当我手动将URL更改为localhost/search?keyword=product+80&page=2时,它可以正常工作,该如何解决??

搜索栏

<form action="{{ route('products.search') }}" method="get" class="search">   
    <input class="form-control" type="text" name="keyword" placeholder="Search">
    <button type="submit" class="btn"><i class="mdi mdi-magnify"></i></button> 
</form>

路线

Route::get('/search', 'ProductController@search')->name('products.search');

控制器

public function search(Request $request)
{
  $keyword = $request->keyword;
  $products = Product::search($keyword)->paginate(20);

  return view('search.index', compact('keyword', 'products'));
}

查看

<div class="container">
  @foreach ($products as $product)
    <div class="col-md-6 col-lg-3">
      <div class="card">
        <div class="card-body">
          <h5 class="card-title">{{ $product->name }}</h5>
        </div>
      </div>
    </div>
  @endforeach

  {{ $products->links() }}
</div>

dd($ request-> all())

array:1 [▼
  "keyword" => "Product 80"
]

dd($ products)

LengthAwarePaginator {#315 ▼
  #total: 100
  #lastPage: 5
  #items: Collection {#340 ▼
    #items: array:20 [▼
      0 => Product {#363 ▶}
      1 => Product {#344 ▶}
      2 => Product {#353 ▶}
      3 => Product {#361 ▶}
      4 => Product {#360 ▶}
      5 => Product {#359 ▶}
      6 => Product {#358 ▶}
      7 => Product {#357 ▶}
      8 => Product {#356 ▶}
      9 => Product {#355 ▶}
      10 => Product {#354 ▶}
      11 => Product {#352 ▶}
      12 => Product {#362 ▶}
      13 => Product {#351 ▶}
      14 => Product {#350 ▶}
      15 => Product {#349 ▶}
      16 => Product {#348 ▶}
      17 => Product {#347 ▶}
      18 => Product {#346 ▶}
      19 => Product {#345 ▶}
    ]
  }
  #perPage: 20
  #currentPage: 1
  #path: "http://marketplace.test/search"
  #query: array:1 [▼
    "query" => "Product 80"
  ]
  #fragment: null
  #pageName: "page"
  +onEachSide: 3
}

dd($ request->关键字)

"Product 80"

dd($ request-> query)

ParameterBag {#50 ▼
  #parameters: array:1 [▼
    "keyword" => "Product 80"
  ]
}

3 个答案:

答案 0 :(得分:0)

我认为您的搜索功能有问题,请尝试以下操作:

public function search(Request $request)
{
  $keyword = $request->keyword;
  $products = Product::where('name','Like',  '%' .$keyword. '%')->paginate(10);

  return view('search.index', compact('keyword', 'products'));
}

答案 1 :(得分:0)

为了使分页正常工作,Laravel需要一个特定的查询名称。因此,只需将您的html更改为:

<input class="form-control" type="text" name="query" placeholder="Search">

并在您的控制器中:

$keyword = $request->query;

答案 2 :(得分:0)

这应该有效:

class BaseClass {
    constructor() { }

    protected sayHello() {
        console.log('hello');
    }
}

class Class extends BaseClass {
    constructor() {
        super();
    }

    protected sayHello() {
        super.sayHello(); 
    }
}

在这里here