0
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備忘録:Laravelでメッセージ投稿フォームを作ったら、ちゃんとDBに入って感動した

Posted at

はじめに

Laravel を使った Web アプリケーション開発において、フォームからの入力を受け取り、バリデーションを通したうえでデータベースに保存するという処理は基本かつ重要な流れです。

今回は、PHP の学習をしている初学者として、実際にフォームを作成し、メッセージを MySQL に保存できたので、その手順を備忘録としてまとめます。

書こうと思ったきっかけ

個人的に PHP のキャッチアップをしたくて Laravel を触り始めました。フォーム入力 → バリデーション → DB保存という基本の流れを自分で手を動かして理解し、記録として残しておきたいと思ったのがきっかけです。

実際のキャッチアップ画面

Screenshot 2025-05-10 at 12.04.52.png

内容

フォームのコード(Bladeテンプレート)

  • ファイルresources/views/message/create.blade.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>メッセージ投稿</title>
</head>
<body>
    <h1>メッセージ投稿フォーム</h1>

    @if(session('success'))
        <p style="color:green">{{ session('success') }}</p>
    @endif

    <form action="/message" method="POST">
        @csrf
        <label>名前: <input type="text" name="name" required></label><br><br>
        <label>メッセージ:<br><textarea name="message" rows="5" cols="40" required></textarea></label><br><br>
        <button type="submit">送信</button>
    </form>
</body>
</html>

コントローラーの処理

  • ファイルapp/Http/Controllers/MessageController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Message;

class MessageController extends Controller
{
    public function create()
    {
        return view('message.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'message' => 'required',
        ]);

        Message::create($validated);

        return redirect('/message')->with('success', '保存しました!');
    }
}

モデル側の設定

  • ファイルapp/Models/Message.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    // 保存を許可するカラムを指定
    protected $fillable = ['name', 'message'];
}

マイグレーションの例

  • ファイルdatabase/migrations/2025_05_05_010232_create_messages_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->string('name');      // 名前
            $table->text('message');     // メッセージ
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('messages');
    }
};

DB保存が成功している確認

  • phpMyAdminMySQL クライアントから messages テーブルを参照し、投稿データが保存されていることを確認

  • Laravel 側でリダイレクト後にメッセージが表示されていることも確認

Screenshot 2025-05-10 at 12.12.58.png

まとめ

Laravel を使ってフォームからメッセージを受け取り、バリデーションを通してデータベースに保存する処理がひと通り実装できました。

個人の備忘録程度の走り書きとなっておりますが、温かい目で見守っていただければ幸いです。

今後は投稿されたデータの一覧表示、編集・削除など CRUD 処理へステップアップしていく予定です。

0
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
0
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?