0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

リソースコントローラー - Laravel学習 #3

0
Last updated at Posted at 2026-06-02

リソースコントローラとは

よく使うメソッドをまとめて生成できる

ターミナル
php artisan make:controller HogeFormController --resource
app/Http/Controler/HogeFormController.php
<?php

namespace App\Http\Controllers;

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

class HogeFormController extends Controller
{
    public function index()
    {
        //
    }

    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        //
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        //
    }

    public function update(Request $request, $id)
    {
        //
    }
    
    public function destroy($id)
    {
        //
    }
}

データテーブルは別途作成
ターミナル
php artisan make:migration create_hoge_table
migrations/日付_create_hoge_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.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hoge_teble', function (Blueprint $table) {
            $table->id();
            $table->string('name', 20);
            $table->string('email', 255);
            $table->longText('url')->nullable();
            $table->boolean('gender');
            $table->tinyInteger('age');
            $table->string('message', 200);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('hoge_table');
    }
};
php artisan migrate

よく使うマイグレーションコマンド集
https://qiita.com/Hashimoto-Noriaki/items/65eb7be82d8b64dde4d6

リソースコントローラーの例

Route
最終的な形

web.php
use App\Http\Controllers\HogeFormController;

// views/hoge-pages/で起こること
Route::prefix('hoge-pages')
->middleware(['auth'])
->controller(HogeFormController::class)
->name('hoge-pages.')
->group(function(){
    Route::get('/', 'index')->name('index');
    Route::get('/create', 'create')->name('create');
    Route::post('/', 'store')->name('store');
    Route::get('/{id}','show')->name('show');
    Route::get('/{id}/edit','edit')->name('edit');
});

require __DIR__.'/auth.php';

index(表示するページ)

Route

web.php
    Route::get('/', 'index')->name('index');

Controller

app/Http/Controler/HogeFormController.php
<?php

use App\Models\HogeForm;

class HogeFormController extends Controller
{
    public function index()
    {
        // idやnameなどのデータの取得する関数 $hogeDates
        $hogeDates = HogeForm::select('id','name','title','created_at') ->get();

        // views/hoges/index.blade.phpを表示
        // compactは関数を配列で格納するPHP関数
        return view('hoge-pages.index', compact('hogeDates'));
    }
}

View

views / hoge-pages / index.blede.php
お問い合わせ一覧

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>名前</th>
      <th>件名</th>
      <th>更新日</th>
      <th>詳細</th>
    </tr>
  </thead>
  <tbody>
    // controllerで定義した$hogesの中にあるデータを表示
    @foreach($hogeDates as $hogeDate)
    <tr>
      <td>{{ $hogeDate->id }}</td>
      <td>{{ $hogeDate->name }}</td>
      <td>{{ $hogeDate->title }}</td>
      <td>{{ $hogeDate->create_at }}</td>
      <td><a href="{{ route('hoge-pages.show', [ 'id' => $hogeDate->id] ) }}">詳細を見る</td>
      // ↑詳細を見るボタンを押すとhttps://hoge-pages/1のようなURLで詳細画面を開く
    </tr>
    @endforeach
  </tbody>
</table>

create(新規登録)

Route

web.php
    Route::get('/create', 'create')->name('create');

Controller

app/Http/Controler/HogeFormController.php
    // indexが書いてある
    
    public function create()
    {
        return view('hoge-pages.create');
    }

View

views / create.blede.php
新規作成

// 新規登録ボタンを押すとstoreによってデータが保存され、index画面に戻る
<form method="POST" action="{{ route('hoge-pages.store') }}">
    @csrf
    <div>
        <label for="name">氏名</label>
        <input type="text" id="name" name="name">
    </div>
    <div>
        <label for="title">件名</label>
        <input type="text" id="title" name="title">
    </div>
    <div>
        <label for="email">メールアドレス</label>
        <input type="text" id="email" name="email">
    </div>
    <div class="relative">
        <label for="url">ホームページ</label>
        <input type="url" id="url" name="url">
    </div>
    <div>
        <label for="gender">性別</label><br>
        <input type="radio" id="gender" name="gender" value="0">
        <label for="gender">男性</label>
        <input type="radio" id="gender" name="gender" value="1">
        <label for="gender">女性</label>
    </div>
    <div>
        <label for="age">年齢</label>
        <select name="age" id="age">
            <option value="0">選択してください</option>
            <option value="1">10</option>
            <option value="2">20</option>
            <option value="3">30</option>
            <option value="4">40</option>
            <option value="5">50</option>
            <option value="6">60~</option>
        </select>
    </div>
    <div>
        <label for="message">お問い合わせ内容</label>
        <textarea id="message" name="message"></textarea>
    </div>

    <button>新規登録する</button>
    
</form>

store(データを保存)

フォームで送られてきた内容を、データベースに新規保存している

Route

web.php
    Route::post('/', 'store')->name('store');

Controller

app/Http/Controler/HogeFormController.php
    // index,createが書いてある
    
    public function store(Request $request)
    {
        // requestから情報を取り出す
        HogeForm::create([
            'name' => $request->name,
            'title' => $request->title,
            'email' => $request->email,
            'url' => $request->url,
            'gender' => $request->gender,
            'age' => $request->age,
            'content' => $request->message,
        ]);

        // indexページへリダイレクトする
        return to_route('hoge-pages.index');
    }

show(保存したデータを表示)

http://hoge/1 などでデータベースに保存された各ユーザーの情報が表示される

Route

web.php
    Route::get('/{id}','show')->name('show');

Controller

app/Http/Controler/HogeFormController.php
    // index,create,storeが書いてある
    
    public function show($id)
    {
        // データベースから、指定した ID の1件を探して取ってくる関数 $hoge
        $hoge = HogeForm::find($id);

        // 性別の関数 $gender
        if($hogeDate->gender === 0){
            $gender = '男性';
        } else {
            $gender = '女性';
        }

        // 年齢の関数 $age
        if($hogeDate->age === 1){
            $age = '~10代';
        } elseif ($hogeDate->age === 2){
            $age = '~20代';
        } elseif ($hogeDate->age === 2){
            $age = '~30代';
        } elseif ($hogeDate->age === 2){
            $age = '~40代';
        } elseif ($hogeDate->age === 2){
            $age = '~50代';
        } else{
            $age = '60代〜';
        }

        // showページにリダイレクト かつ 変数を渡す
        // compactは変数名のリストをビューに渡すための配列にまとめる PHP の関数
        return view('hoge-pages.show', compact('hoge', 'gender', 'age'));
    }
  • findの詳しい説明

View

views / hoge-pages / show.blede.php
詳細画面

    <div>
        <label for="name">氏名</label>
        {{ $hogeDate->name }}
    </div>
    <div>
        <label for="title">件名</label>
        {{ $hogeDate->title }}
    </div>
    <div>
        <label for="email">メールアドレス</label>
        {{ $hogeDate->email }}
    </div>
    <div class="relative">
        <label for="url">ホームページ</label>
        {{ $hogeDate->url }}
    </div>
    <div>
        <label for="gender">性別</label><br>
        {{ $gender }}
    </div>
    <div>
        <label for="age">年齢</label>
        {{ $age }}
    </div>
    <div>
        <label for="hoge">お問い合わせ内容</label>
        {{ $hogeDate->content }}
    </div>

    // idに合うユーザーのeditページに飛ぶ
    <form method="get" action="{{ route('hoges.edit', ['id' => $hogeDate->id] ) }}">
        <button>編集する</button>
    </form>
  • ルートパラメーター
    {{ route('hoge.show', ['id' => $hogeDate->id ] ) }}

edit(保存されたデータを編集)

Route

web.php
    Route::get('/{id}/edit','edit')->name('edit');

Controller

app/Http/Controler/HogeFormController.php
    // index,create,store,showが書いてある
    
    public function edit($id)
    {
        $hogeDate = ContactForm::find($id);

        return view('contacts.edit', compact('contact'));
    }

View

views / hoge-pages / edit.blede.php
編集画面

// 後ほどupdateを作る
<form method="POST" action="{{ route('contacts.update', ['id' => $hogeDate->id]) }}">
    @csrf
    <div>
        <label for="name">氏名</label>
        <input type="text" id="name" name="name" value="{{ $hogeDate->name }}">
    </div>
    <div>
        <label for="title">件名</label>
        <input type="text" id="title" name="title" value="{{ $hogeDate->title }}">
    </div>
    <div>
        <label for="email">メールアドレス</label>
        <input type="text" id="email" name="email" value="{{ $hogeDate->email }}">
    </div>
    <div class="relative">
        <label for="url">ホームページ</label>
        <input type="url" id="url" name="url" value="{{ $hogeDate->url }}">
    </div>
    <div>
        <label for="gender">性別</label><br>
        
        <input type="radio" id="gender" name="gender" value="0" @if($hogeDate->gender === 0) checked @endif>
        <label for="gender">男性</label>
        
        <input type="radio" id="gender" name="gender" value="1" @if($hogeDate->gender === 1) checked @endif>
        <label for="gender">女性</label>
    </div>
    <div>
        <label for="age">年齢</label>
        <select name="age" id="age">
            <option value="0">選択してください</option>
            <option value="1" @if($hogeDate->age === 1) selected @endif>10</option>
            <option value="2" @if($hogeDate->age === 2) selected @endif>20</option>
            <option value="3" @if($hogeDate->age === 3) selected @endif>30</option>
            <option value="4" @if($hogeDate->age === 4) selected @endif>40</option>
            <option value="5" @if($hogeDate->age === 5) selected @endif>50</option>
            <option value="6" @if($hogeDate->age === 6) selected @endif>60~</option>
        </select>
    </div>
    <div>
        <label for="hoge">お問い合わせ内容</label>
        <textarea id="content" name="content">{{ $hogeDate->content }}</textarea>
    </div>

    <button>更新する</button>

</form>

update(データの更新)

Route

web.php
    Route::post('/{id}','update')->name('update');

Controller

app/Http/Controler/HogeFormController.php
    // index,create,store,show,editが書いてある
    
    public function update(Request $request, $id)
    {
        $hogeDate = ContactForm::find($id);
        $hogeDate->name = $request->name;
        $hogeDate->title = $request->title;
        $hogeDate->email = $request->email;
        $hogeDate->url = $request->url;
        $hogeDate->gender = $request->gender;
        $hogeDate->age= $request->age;
        $hogeDate->content = $request->content;
        $hogeDate->save();

        return to_route('contacts.index');

    }

destroy(データの削除)

Route

web.php
    Route::post('/{id}/destroy','destroy')->name('destroy');

Controller

app/Http/Controler/HogeFormController.php
    // index,create,store,show,edit,updateが書いてある
    
    public function destroy($id)
    {
        $contact = ContactForm::find($id);
        $contact->delete();

        return to_route('contacts.index');
    }

View

views / hoge-pages / show.blede.php
詳細画面

    <div>
        <label for="name">氏名</label>
        {{ $hogeDate->name }}
    </div>
    <div>
        <label for="title">件名</label>
        {{ $hogeDate->title }}
    </div>
    <div>
        <label for="email">メールアドレス</label>
        {{ $hogeDate->email }}
    </div>
    <div class="relative">
        <label for="url">ホームページ</label>
        {{ $hogeDate->url }}
    </div>
    <div>
        <label for="gender">性別</label><br>
        {{ $gender }}
    </div>
    <div>
        <label for="age">年齢</label>
        {{ $age }}
    </div>
    <div>
        <label for="hoge">お問い合わせ内容</label>
        {{ $hogeDate->content }}
    </div>

    <form method="get" action="{{ route('hoges.edit', ['id' => $hogeDate->id] ) }}">
        <button>編集する</button>
    </form>

    // 削除ボタンを追加する
    <form method="post" action="{{ route('contacts.destroy', ['id' => $contact->id] ) }}" id="delete_{{ $contact->id }}">
       @csrf
       <a href="#" data-id="{{ $contact->id }}" onclick="deletePost(this)">削除する</a>
     </form>

    <script>
        function deletePost(e){
            'use strict'
            if(confirm('本当に削除していいですか?')){
                document.getElementById('delete_' + e.dataset.id).submit()
            }
        }
    </script>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?