前回の BBS は操作が分かりずらかったので作り直しました。デザインも変わりました。
WEB アプリケーションには、CRUD という機能をつけると良いとされています。
CRUD とは、Create (作成)、Read (読み込み)、Update (更新)、Delete (削除)の頭文字をとったものです。
ここでは、Read (読み込み) 機能を付けます。
インデックスページに Post モデルのデータをわたすため、 app / Http / Controllers の PostController.php を次のようにコーディングします。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post; // Post モデルを使えるようにしています
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->get(); // Post モデルのすべてのデータを新しい順に読み込んでいます
// 次のコードで with() を使って、posts という名前で
// Post モデルのデータを index.blade.php に渡しています
return view('index')->with(['posts' => $posts]);
}
}
resources / views / index.blade.php を次のように書きかえてください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BBS</title>
<link rel="stylesheet" href="{{ url('style.css')}}">
</head>
<body>
<div class="container">
<h1 class="margin-zero">BBS</h1>
<ul>
@forelse ($posts as $post)
<li>
<div class="post-sub">
<p class="v-center">{{Str::limit($post->body, 80)}}</p>
</div>
</li>
@empty
<li class="no-title">No post!</li>
@endforelse
</ul>
</div>
</body>
</html>
php artisan serve で BBS アプリを起動して、localhost:8000 で確認してください。
インデックスページの表示を整えるため、public フォルダに、次のファイルを style.css というファイル名で作ってください。
body {
background-color: #efefef;
color: gray;
font-family: sans-serif;
}
.container {
width: 400px;
margin: 32px auto;
}
h1 {
font-size: 20px;
color: gray;
}
ul {
padding-left: 0;
}
li {
list-style: none;
margin-top: 16px;
}
.post-sub {
width: 100%;
height: 80px;
background-color: white;
border-radius: 4px;
border: solid 1px lightgray;
}
.v-center {
margin: 8px;
}
.no-title {
font-size: small;
text-align: center;
color: gray;
}
php artisan serve で BBS アプリを起動して、localhost:8000 で確認してください。