ページネーションを実装中にエラーになったので、備忘録として残しておきます。
エラー内容
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: /var/www/html/resources/views/articles/index.blade.php)
該当するソースコード
ArticleController.php
public function index(Request $request)
{
//検索機能
$search = $request->input('search');
$query = Article::query();
//タイトルと本文の曖昧検索を実施
if (!empty($search)) {
$query->where('title', 'LIKE', "%{$search}%")
->orWhere('body', 'LIKE', "%{$search}%");
}
$articles = $query->paginate(10)->sortByDesc('created_at');
return view('articles.index', ['articles' => $articles]);
}
index.blade.php
@extends('app')
@section('title', '一覧ページ')
@section('content')
@include('nav')
<div class="container">
<div class="row">
<div class="col-md-12">
@guest
<img src="/images/Construction-pana_r1.png" width="100%">
@endguest
<form method="GET" action="{{ route('articles.index') }}" class="d-flex">
<input class="form-control me-2 mt-3" name="search" type="search" placeholder="検索" aria-label="Search">
<button class="btn btn-outline-success mt-3 mb-0 ml-0 py-0" type="submit"><i class="fas fa-search"></i></button>
</form>
@foreach($articles as $article)
@include('articles.card')
@endforeach
</div>
{{ $articles->links() }}
</div>
</div>
@endsection
sortByDesc
をorderByDesc
にすることで解決
$articles = $query->paginate(10)->sortByDesc('created_at');
だと「10件取得した結果から並べ替える」になっています。
$articles = $query->orderByDesc('created_at')->paginate(10);
に修正することで、「並べ替えた結果から10件取得」ことになります。
また、sortByDesc()
はコレクション(配列を拡張した(機能を加えた)もの)で返していたのが原因だったと考えています。
クエリビルダの機能であるorderByDesc()
を使用することで、指定したカラムでクエリ結果をソートし表示することができたと思います。