Laravel12での各種設定等・便利機能メモ

2025年4月11日

データベースにレポートを保存する形式のアプリを作る。

モデルの生成

php artisan make:model Report -m

-mを入れることで、モデルファイル作成時に、マイグレートファイルも同時に作成

マイグレーションファイルは作るが

public function up(): void
    {
        Schema::create('reports', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('business_id');
            $table->unsignedBigInteger('user_id');
            $table->timestamp('report_date')->nullable();
            $table->unsignedBigInteger('shift_id');
            $table->unsignedBigInteger('situation_id');
            $table->timestamp('arrival_time')->nullable();
            $table->timestamps();
        });
    }

->nullable()でNULLを可能にする。
Laravelの timestamp() カラムは、NULLを許可しない場合が多いです。

モデル、1対多のリレーション

ModelをUserと結びつけるには新しく作ったモデル内で

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Report extends Model
{
    public function user() {
        return $this->belongsTo(User::class);
    }
}

とする。
さらに、User.php側も

<?php

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * Get the user's initials
     */
    public function initials(): string
    {
        return Str::of($this->name)
            ->explode(' ')
            ->map(fn (string $name) => Str::of($name)->substr(0, 1))
            ->implode('');
    }
    public function reports() {
        return $this->hasMany(Report::class);
    }
}


とする。リレーションを作成したら、その情報をデータベース上のテーブルにも反映。

$table->foreignId('user_id');

などと直して

php artisan migrate:rollback
php artisan migrate

これでOK。

Viewファイルで新規画面制作

ビューファイルの作成→コントローラー→ルート設定の順番に作る。

viewファイルを作る

resources/viewsの中にディレクトリ「report」を作る。
その中に「create.blade.php」を作る。

リソースコントローラーの設定

php artisan make:controller コントローラー名 --resource

今回は「report」のものを作るので

php artisan make:controller ReportController --resource --model=Report

になる。すると
\app\Http\Controllers\ReportController.php
ができる。

–model=Reportを付けたので
use App\Models\Report;が追記されている。

画面表示部分

ReportController.phpのcreate部分に

public function create()
    {
        return view('report.create');
    }

を追記。
さっき作った
resources/views/report/create.blade.php
を使うよと設定。
report.createの前半はディレクトリ、後半はファイル名。

web.phpのルート設定

次はルート設定。
routes/web.phpに書き込む。
今回リソースコントローラーなので
上の方で

use App\Http\Controllers\ReportController;

ReportControllerを使うよと宣言して

Route::middleware(['auth'])->group(function () {

//最初から入っているものは省略
	Route::resource('report', ReportController::class);
}

と入れる。
これで

Route::get('report', [ReportController::class, 'index'])->name('report.index');
Route::get('report/create', [ReportController::class, 'create'])->name('report.create');
Route::post('report', [ReportController::class, 'store'])->name('report.store');
Route::get('report/{report}', [ReportController::class, 'show'])->name('report.show');
Route::get('report/{report}/edit', [ReportController::class, 'edit'])->name('report.edit');
Route::patch('report/{report}', [ReportController::class, 'update'])->name('report.update');
Route::delete('report/{report}', [ReportController::class, 'destroy'])->name('report.destroy');

と同じ意味になる。
{report}の部分は各投稿のidが数字で入る。

ここまでできたら/report/createで表示できるはず。
投稿するものなので投稿を保存するフェーズへ。

データベースにレポートを保存

コントローラーとビューファイルとデータベース全て揃ったら、処理を実行できる。

フォームを作る。

<form method="post" action="{{ route('report.store') }}" enctype="multipart/form-data">
<div class="w-full flex flex-col">
                        <label for="title" class="font-semibold leading-none mt-4">件名</label>
                        <input type="text" name="title"
                            class="w-auto py-2 pl-2 placeholder-gray-300 border border-gray-300 rounded-md" id="title" value="{{old('title')}}">
                    </div>
</form>

こんな感じ。

{{old('title’)}}みたいにするのは
二重波カッコ{{}}で囲むだけで、エスケープ処理ができる。というか必須で。
oldは入力してエラーになっても前回入力していた内容が残る。
なので全部この形式でいい。

ルートはすでに今回リソースコントローラーなので決まってる。
今回のやり方で作ったものは全部これになる。

indexメソッド /report (URL) report.index(ルート名)
createメソッド /report/create (URL) report.create(ルート名)(HTTPメソッド:GET)
storeメソッド /report (URL) report.store(ルート名)(HTTPメソッド:POST)
showメソッド /report/{report} (URL) report.show(ルート名)(HTTPメソッド:GET)
editメソッド /report/{report}/edit (URL) report.edit(ルート名)(HTTPメソッド:GET)
updateメソッド /report/{report} (URL) report.update(ルート名)(HTTPメソッド:PUT/PATCH)
destroyメソッド /report/{report} (URL) report.destroy(ルート名)(HTTPメソッド:DELETE)

なので、
データを保存する用のstoreメソッドを実行するために
モデルに処理を書く。

モデルに処理を書く

まずは入力したものを送信する許可を与える。
protected $fillableで入力された項目を送信することを許可。

app/models/Report.php

protected $fillable = [
        'situation_id',
        'arrival_time_day',
        'arrival_time_minutes',
    ];

みたいな。

コントローラーに処理を書く

次はコントローラーに処理を書く。ついでにバリデーションも。

App/Http/Controllers/ReportController.php


※順次追記します

未分類

Posted by bistro