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?

More than 1 year has passed since last update.

Laravel 9 Todo-アプリケーション with Mysql 

Last updated at Posted at 2022-10-31

laravel9.png

開発環境

image.png

image.png

主に使うコマンド

image.png
image.png

Laravelプロジェクトの作成

terminal
    laravel new todo-app
    cd todo-app

開発用のサーバーを起動

terminal
    php artisan serve

image.png

モデルの作成

terminal
    php artisan make:model Todo
Todo.php
    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    class Todo extends Model
    {
        use HasFactory;
    
        protected $guarded = array('id');
    
        public static $rules = array(
            'task' => "required", 
        );
    }

マイグレーションファイルの作成

terminal
    php artisan make:migration create_todos_table

create_todos_tableにカラムを追加

create_todos_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('todos', function (Blueprint $table) {
                $table->increments('id');
                $table->string('task');
                $table->boolean('completed');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('todos');
        }
    }; 

Mysqlにテーブルを作成

terminal
    php artisan migrate

image.png

image.png

todosテーブルにデータの挿入

1,seederを作成して挿入する方法

terminal
    php artisan make:seeder TodoSeeder

TodoSeeder.php

TodoSeeder.php
   <?php

    namespace Database\Seeders;
    
    use Illuminate\Database\Console\Seeds\WithoutModelEvents;
    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\DB;
    
    class TodoSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            DB::table('todos')->insert([
                [
                    'task' => 'Buy Car',
                    'completed' => false,
                ],
                [
                    'task' => 'Go to see the doctor',
                    'completed' => false,
                ],
                [
                    'task' => 'Watch movie',
                    'completed' => false,
                ],
            ]);
        }
    } 
terminal
    php artisan db:seed --class=TodoSeeder

image.png

2, ダミーデータを作成してテーブルに挿入する方法

①Todoモデルを作成
②Todoファクトリを作成

terminal
    php artisan make:model Todo
    php artisan make:factory TodoFactory

DatabaseSeeder.phpを変更

DatabaseSeeder.php
    <?php
    
    namespace Database\Seeders;
    
    // use Illuminate\Database\Console\Seeds\WithoutModelEvents;
    
    use App\Models\Todo;
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
            // \App\Models\User::factory(10)->create();
    
            // \App\Models\User::factory()->create([
            //     'name' => 'Test User',
            //     'email' => 'test@example.com',
            // ]);
    
            Todo::factory(5)->create();
        }
    }   

seedを実行

terminal
    php artisan db:seed

テーブルとseedのりフレッシュ

terminal
    php artisan migrate:fresh --seed

ステータスの確認

terminal
    php artisan migrate:status

リセット

terminal
    php artisan migrate:reset

⇒テーブルを空にする

リフレッシュ

terminal
    php artisan migrate:refresh

⇒reset →migrate

Todoコントローラーの作成

terminal
   php artisan make:controller TodoController --resource 

TodoController.phpに追記

TodoController.php
<?php

namespace App\Http\Controllers;

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

class TodoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $todos = Todo::latest()->paginate(5);
        return view('todos.index', ["todos" => $todos]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('todos.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, Todo::$rules);
        $todo = new Todo;
        $form = $request->all();
        unset($form['_token']);
        $todo->fill($form)->save();
        return redirect('/todos');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, $id)
    {
       $todo = Todo::find($request->id);
       return view('todos.show', ['todo' => $todo]); 
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $todo = Todo::find($request->id);
        return view('todos.edit', ['todo' => $todo]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, Todo::$rules);
        $todo = Todo::find($request->id);
        $form = $request->all();
        unset($form['_token']);
        $todo->fill($form)->save();
        return redirect('/todos');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $todo = Todo::fubd($request->id)->delete();
        return redirect('/todos');
    }
}

viewsフォルダにtodosフォルダと各blade.phpを作成

image.png

routesフォルダのweb.phpファイルにルーティングを設定

web.php
// 全レコード表示 Display a listing of the resource.
Route::get("/todos", [TodoController::class, 'index']);

// 新規作成 Show the form for creating a new resource.
Route::get("/todos/create", [TodoController::class, 'create']);
Route::post("/todos/create", [TodoController::class, 'store']);

// 編集 Show the form for editing the specified resource.
Route::get("/todos/edit/{id}", [TodoController::class, 'edit']);
Route::put("/todos/edit/{id}", [TodoController::class, 'update']);

// 詳細表示 Display the specified resource.
Route::get('/stationaries/show/{id}', [TodoController::class, 'show']);

// 削除 Remove the specified resource from storage.
Route::delete("/todos/delete/{id}", [TodoController::class, 'destroy']);

layout.balde.phpを作成

layout.blade.php
    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Todo</title>
        <style>
            *{
                text-align: center;
                align-items: center;
                margin: auto;
            }
            footer{
                text-align: right;
                font-size: 10px;
                margin: 10px;
                border-bottom: solid 1px #ccc;
                color: #ccc;
            }
            th{
                background-color: #999;
                color: #fff;
                padding: 5px 10px;
            }
            td{
                border: solid 1px #aaa;
                color: #999;
                padding: 5px 10px;
            }
        </style>
        
    </head>
    <body>
    
        <header>
            ヘッダー
        </header>
        <nav>
            <a href="/todos">Home</a>
            <a href="/todos/add">New Task</a>
        </nav>
    
        <h1>Todos</h1>
        {{-- VIEW OUTPUT --}}
    
        <main>
            {{-- error --}}
            @if (count($errors) > 0)
            <div>
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
    
            @yield('content')
        </main>
    
        <footer>
            copyrigh 2022 iwasaki
        </footer>
    
        
    </body>
    </html>

auth認証

terminal
    composer require laravel/breeze --dev
    php artisan breeze;install
    npm install
    npm run dev

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?