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

![laravel9.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/9e2bd5e0-6215-f9cc-486d-b266fc6cf48c.png)


# 開発環境
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/9c0aefcd-d806-4252-45d7-206d81e22c64.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/7320a927-5b4b-8de7-1da6-8a5997c3688a.png)

# 主に使うコマンド
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/4c22e349-6c43-f669-1261-5d56bdf75ad6.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/d48dce59-2ed1-410d-27c0-6f49a327345a.png)



# Laravelプロジェクトの作成
```terminal:terminal
    laravel new todo-app
    cd todo-app
```

# 開発用のサーバーを起動
```terminal:terminal
    php artisan serve
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/81aff4bb-b664-351d-76c0-b9610e71e989.png)







# モデルの作成
```terminal:terminal
    php artisan make:model Todo
```

```php: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:terminal
    php artisan make:migration create_todos_table
```

# create_todos_tableにカラムを追加
```php: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:terminal
    php artisan migrate
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/4bab9f3c-64e8-937b-90c6-fbe37e3b3c85.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/eaf5c0e9-0ba4-f35b-5b9f-b41321bebd80.png)

# todosテーブルにデータの挿入
1,seederを作成して挿入する方法
```terminal:terminal
    php artisan make:seeder TodoSeeder
```



# TodoSeeder.php
```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:terminal
    php artisan db:seed --class=TodoSeeder
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/d177f6e9-9f1f-bc31-6a96-eaab84d29132.png)

2, ダミーデータを作成してテーブルに挿入する方法
>①Todoモデルを作成
②Todoファクトリを作成

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

# DatabaseSeeder.phpを変更
```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:terminal
    php artisan db:seed
```

# テーブルとseedのりフレッシュ
```terminal:terminal
    php artisan migrate:fresh --seed
```

# ステータスの確認
```terminal:terminal
    php artisan migrate:status
```

# リセット
```terminal:terminal
    php artisan migrate:reset
```
⇒テーブルを空にする

# リフレッシュ
```terminal:terminal
    php artisan migrate:refresh
```
⇒reset →migrate


# Todoコントローラーの作成
```terminal:terminal
   php artisan make:controller TodoController --resource 
```

# TodoController.phpに追記
```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](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/654025/54d45931-ecdf-cc8f-0d9e-382bb203d162.png)

# routesフォルダのweb.phpファイルにルーティングを設定
```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を作成
```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:terminal
    composer require laravel/breeze --dev
    php artisan breeze;install
    npm install
    npm run dev

```