css・bootstrap・ページネーション実装
1.目的
投稿したものをページネーションを使い表示することができるようにします。また、cssを使うことができるようにし見た目を整えることができるようにします。
2.必要なもの
なし
3.方法
○css・*bootstrap導入
①app/public/resources/views/items/layouts/app.blade.phpを以下のように編集します。
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
//以下追加
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
//ここまで
</head>
//省略
*bootstrapは、上記の方法でも導入はできるがterminalで以下のコマンドを入力することでもできます。
% composer require laravel/ui
% php artisan ui bootstrap
% npm install && npm run dev
*bootstrapというのは、フレームワークの1つでありweb制作者の作業を効率化させるために作られたcssやjavascriptの雛形です。
bootstrapは、次に実装するページネーションの作成にも使われている機能です。
○ページネーションの実装
①ItemsControllerを以下のように編集しページネーションを使った1ページあたりの表示数を決めます。
//省略
public function index()
{
//以下追加
$items = Item::orderBy('created_at','desc')->paginate(5);
return view('items.index',compact('items'));
}
//省略
ここでは、投稿ページに投稿したものを5つ表示しています。
②views/items/index.blade.phpを以下のように編集します。
@extends('layouts.app')
@section('content')
<h1>hello World</h1>
<a href="{{ url('item/create') }}" >投稿</a>
<h2>投稿されたもの</h2>
@foreach($items as $item)
<a href="{{ action('ItemsController@show', $item->id) }}">
<div>{{ $item->name }}</div>
</a>
@endforeach
//以下追記
<div class="row">
<div class="col-md-4 offset-md-4">
{{ $items->links('pagination::bootstrap-4') }}
</div>
</div>
//ここまで
@endsection
ここでページネーションを埋め込んでいます。'pagination::bootstrap-4'を読み込んでいないとページネーションのレイアウトが崩れてしまいます。
そのようになってしまうのは、LaravelのページネーションがデフォルトでTailwind互換になっているからです。
4.まとめ
これにてページネーションの実装は完成デす。
以下のように表示されたらOK!!です。
ありがとうございました。
この記事が気に入ったらサポートをしてみませんか?