前回の記事の続きで、検索フォームにページネーションを追加してみます。
サンプルコード
app\Http\Controllers\SearchController.php
<?php
namespace App\Http\Controllers;
use App\Autumn2016;
use Request;
class SearchController extends Controller
{
public function getIndex()
{
// 検索するテキスト取得
$s_title = Request::get('s_title');
$s_category = Request::get('s_category');
$s_production = Request::get('s_production');
$s_actor = Request::get('s_actor');
$query = Autumn2016::query();
// 検索するテキストが入力されている場合のみ
if(!empty($s_title)) {
$query->where('title', 'like', '%'.$s_title.'%');
}
if(!empty($s_category)) {
$query->where('category', 'like', '%'.$s_category.'%');
}
if(!empty($s_production)) {
$query->where('production', 'like', '%'.$s_production.'%');
}
if(!empty($s_actor)) {
$query->where('actor', 'like', '%'.$s_actor.'%');
}
$data = $query->paginate(3);
return view('search.index', compact('data', 's_title', 's_category', 's_production', 's_actor'));
}
}
ページネーションのURLに検索用のパラメータを付与するようにします。
resources\views\search\index.blade.php
{!! Form::open(['method' => 'GET']) !!}
タイトル:{!! Form::text('s_title', $s_title) !!}
カテゴリ:{!! Form::text('s_category', $s_category) !!}
制作会社:{!! Form::text('s_production', $s_production) !!}
声優:{!! Form::text('s_actor', $s_actor) !!}
{!! Form::submit('検索') !!}
{!! Form::close() !!}
@foreach($data as $item)
<div>
<div>{{{ $item->id }}}</div>
<div>{{{ $item->title }}}</div>
<div>{{{ $item->category }}}</div>
<div>{{{ $item->production }}}</div>
<div>{{{ $item->actor }}}</div>
</div>
<hr>
@endforeach
{{ $data->appends(['s_title'=>$s_title,'s_category'=>$s_category,'s_production'=>$s_production,'s_actor'=>$s_actor])->links() }}
カテゴリに「漫画」と入れて検索すると、以下のように表示されました。

次のページへ移動しても、検索内容が維持されています。

【参考サイト】
コメントが承認されるまで時間がかかります。