Laravel | Ledger | Read の実装

ホーム  

概要

このページは2025年8月3日15時10分に書き換えました。データが一つ増えています。

WEB アプリケーションには、CRUD という機能をつけると良いとされています。

CRUD とは、Create (作成)、Read (読み込み)、Update (更新)、Delete (削除)の頭文字をとったものです。

ここでは、Read (読み込み) 機能を付けます。


インデックスページにデータを渡す

インデックスページに Post モデルのデータをわたすため、 app / Http / Controllers の NLController.php を次のようにコーディングします。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\NL;  // NL モデルを使えるようにしています

class PostController extends Controller
{
    public function index()
    {
        // 次のコードで、NL モデルのすべてのデータを読み込んでいます
        $n_l_s = NL::all();
        // 次のコードで with() を使って、n_l_s という名前で、NL モデルのデータを index.blade.php に渡しています
        return view('index')->with(['n_l_s'=>$n_l_s]);
    }
}


インデックスページの変更

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">
    <link rel="stylesheet" href="{{url('style.css')}}">
    <title>Ledger</title>
</head>
<body>
    <h1>生徒台帳</h1>
    <div id="container">
    <div class="a-right">
        <button type="button">追加</button>
    </div>
    <table id="table-fixed">
    <tr>
        <th>氏名</th>
        <th>性別</th>
        <th>学年</th>
        <th>得意科目</th>
        <th>成績</th>
    </tr>
    @foreach ($n_l_s as $n_l_)
    <tr>
        <td>{{$n_l_->name}}</td>
        <td>
        @if($n_l_->gender)
        男性
        @else
        女性
        @endif
        </td>
        <td>{{$n_l_->year}}年</td>
        <td>{{$n_l_->favo}}</td>
        <td class="spc">
            <div>
            {{$n_l_->grades}}点
            </div>
            <div>
            <button type="button">詳細</button>
            </div>
        </td>
    </tr>
    @endforeach
    </table>
    </div>
</body>
</html>

php artisan serve で Ledger アプリを起動して、localhost:8000 で確認してください。


CSS ファイルの作成

インデックスページの表示を整えるため、public フォルダに、次のファイルを style.css というファイル名で作ってください。

body {
    font-family: sans-serif;
    color: gray;
}

h1 {
    margin: 32px;
    font-size: larger;
    text-align: center;
}

#container {
    width: 90%;
    margin: 0 auto;
}

.a-right {
    text-align: right;
}

button {
    color: gray;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 32px;
}

#table-fixed {
    table-layout: fixed;
}

th {
    background-color: #dfdfdf;
    border: 1px solid;
    padding: 8px;
}

td {
    border: 1px solid;
    padding: 8px;
}

.spc {
    display: flex;
    border-top: 0;
    border-left: 0;
}

.spc>div:nth-child(1) {
    width: 50%;
    text-align: left;
}

.spc>div:nth-child(2) {
    width: 50%;
    text-align: right;
}

php artisan serve で Ledger アプリを起動して、localhost:8000 で確認してください。



1123 visits
Posted: Aug. 02, 2025
Update: Aug. 03, 2025

ホーム   目次