3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP学習3日目】MVCパターンを理解してみた

Posted at

はじめに

プログラミング学習3日目として、LaravelのMVCパターンに挑戦しました。
MAMP環境(PHP 8.4.1)でLaravel 11を使用し、実際に手を動かしながら学んだ過程を詳しく記録します。


開発環境

  • OS: macOS
  • PHP: 8.4.1(MAMP使用)
  • Laravel: 11.x
  • データベース: SQLite

今回実装した機能

  • ルーティングの設定
  • Controllerの作成と処理
  • Bladeテンプレートでの画面表示
  • Modelとマイグレーションでのデータベース操作
  • Tinkerを使ったデータ操作

Step 1: ルーティングの設定

まず、routes/web.php でルーティングを設定しました。

Route::get('/hello', [HelloController::class, 'index'])->name('hello.index');
Route::get('/hello/{id}', [HelloController::class, 'show']);
Route::get('/posts', [HelloController::class, 'posts']);

ルーティングの説明

Route::get('/hello', [HelloController::class, 'index'])

/hello にアクセスすると、HelloController の index メソッドが実行される

->name('hello.index')

ルートに名前を付けることで、Bladeテンプレート内で route('hello.index') として参照可能

Route::get('/hello/{id}', ...)

URLパラメータ {id} を受け取るルート

Route::get('/posts', ...)

投稿一覧を表示するルート


Step 2: Controllerの作成

コマンド実行

php artisan make:controller HelloController

HelloControllerの実装

app/Http/Controllers/HelloController.php に以下を実装した

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class HelloController extends Controller
{
    public function index()
    {
        return view('hello', [
            'name' => 'Laravel',
            'version' => app()->version()
        ]);
    }

    public function show($id)
    {
        return view('hello', ['name' => "User ID: {$id}"]);
    }

    public function posts()
    {
        $posts = Post::all();
        return view('posts', compact('posts'));
    }
}

Controllerの説明

  • index():Hello画面を表示、Bladeテンプレートにnameとversionを渡す
  • show($id):URLパラメータを受け取り、Bladeテンプレートに渡す
  • posts():データベースから全投稿を取得し、postsビューに渡す

Step 3: Modelとマイグレーションの作成

コマンド実行

php artisan make:model Post -m

マイグレーションファイルの確認
database/migrations/xxxx_create_posts_table.php

public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Postモデルの実装
app/Models/Post.php に以下を追加した

protected $fillable = ['title', 'content'];

マイグレーション実行

php artisan migrate

スクリーンショット 2025-08-14 16.33.42.png

マイグレーションの説明

  • $table->id():主キー
  • $table->string('title'):タイトル
  • $table->text('content'):本文
  • $table->timestamps():作成日時・更新日時を自動管理
  • $fillable:mass assignmentで一括作成可能なカラム

Step 4: Bladeテンプレートの作成

resources/views/hello.blade.php

blade.php
<h1>Hello, {{ $name }}!</h1>
@if(isset($version))
    <p>Laravel Version: {{ $version }}</p>
@endif

resources/views/posts.blade.php

blade.php
<h1>Posts</h1>
<ul>
    @foreach($posts as $post)
        <li>{{ $post->title }} - {{ $post->content }}</li>
    @endforeach
</ul>
<a href="{{ route('hello.index') }}">Back to Hello</a>

Bladeテンプレートの説明

  • {{ $name }}:変数を出力(自動エスケープ)
  • @if:条件分岐
  • @foreach:ループ処理
  • {{ route('hello.index') }}:名前付きルートURLを生成

スクリーンショット 2025-08-14 15.58.16.png
スクリーンショット 2025-08-14 15.58.24.png
スクリーンショット 2025-08-14 15.58.42.png


Step 5: Tinkerでのデータ操作

Tinkerの起動

php artisan tinker

データの作成

use App\Models\Post;
Post::create(['title' => 'First Post', 'content' => 'This is a test']);

データの確認

Post::all();
Post::latest()->first();

Tinkerの説明

  • LaravelのREPL環境
  • Post::create():新しいレコードを作成
  • Post::all():全レコード取得
  • Post::latest()->first():最新レコード取得

発生したエラーと解決方法

1. "Class Post not found"

  • 原因:Tinkerでモデルクラスがインポートされていない
  • 解決
use App\Models\Post;

2. “syntax error, unexpected token”

  • 原因:Bladeテンプレートに <?php タグが記載されていた
  • 解決:Bladeでは <?php タグは不要なので削除する

3. Mass assignment error

  • 原因:$fillable プロパティが設定されていない
  • 解決:Post モデルに以下を追加

protected $fillable = ['title', 'content'];


動作確認

アクセス可能なURL


学んだことのまとめ

MVCパターンの理解

  • Model(Postモデル):データベースとの接続、データ操作
  • View(Bladeテンプレート):ユーザーに表示する画面
  • Controller(HelloController):リクエストを受け取り、ModelとViewを制御

Laravelの便利機能

  • Artisan:make:controller、make:model などのコマンド
  • マイグレーション:データベーススキーマのバージョン管理
  • Eloquent ORM:データベース操作を簡単に
  • Blade:テンプレートエンジンで動的なHTML生成
  • ルーティング:URLとControllerメソッドの紐付け

次回の課題

  • フォーム機能の実装(新規投稿作成)
  • バリデーション機能の追加
  • ページネーション機能
  • CSS(Bootstrap/Tailwind)でのスタイリング

まとめ

初心者でも一日でLaravelのMVCパターンを一通り体験することができました。
特に印象的だったのは、Artisanコマンドの便利さとBladeテンプレートの直感的な記法です。

エラーで躓くこともありましたが、一つずつ解決していくことで理解が深まりました。
次回はより実用的な機能を実装していきたいと思います。


3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?