1
0

More than 1 year has passed since last update.

todolist_php

Last updated at Posted at 2021-12-24

環境

以下の環境で作成します。

mac
php8
laravel8
vscode(なんでも良い)
php artisan serve(laravelのbuilt in サーバ)
mysql(ローカルにインストールする)

mysqlのインストール

homebrewを使えばできる
https://prog-8.com/docs/mysql-env
*上記ドキュメントは、mysql5.7を使ってますが、平塚は8です。ここはどっち使ってもいいです。

インスールできてるか確認

以下のコマンドでmysqlのバージョンが取得できればOK

mysql --version

一応ログインできるか確認

brew services start mysql
mysql -uroot

*上の例では、rootのパスワードをセットしに行ってますが、そこは余力があれば対応しましょう。
*基本的に自分のmacの勉強用なら、rootのパスワードはあってもなくてもどっちでもいいと思います。
大した情報を管理することもないと思うので。ただし自己責任で。

いよいよ todo listの作成

https://qiita.com/s_harada/items/39cfbd64a6df4f2ccf5d
をベースにしてますが、ちょっと変えてます。

データベースの作成

これから作るtodoリストのデータベースを作成しておきましょう

mysql> create database todo_db;

laravelインストール

brew install composer
composer create-project "laravel/laravel=6.*" プロジェクト名

プロジェクト作成

既にcomposerが入ってる人は以下

laravel new todo_list

model,view,controllerを作成

todoのデータを格納するモデルを作成していきます。
laravelは

model(データを扱うところ。データベースと一番近いものと覚えておけば最初はいいです。)
view(実際に画面に表示する部分)
controller(modelからとってきたデータをviewに渡す部分)

で構成されており、これらをそれぞれ作らないといけないです。

まずは、データベースにtableを作らないと意味ないので、migrationを作成します。
*最近のwebフレームワークは、言語問わず、データベースにtableを作る際はmigrationを使います。

php artisan make:migration create_todos_table --create=todos

必要なカラム

todoですること
締め切り(いつまでに完了するか)
タスクのstatus

上記をmigrationで入れると

<?php

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

class CreateTodosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('task');  // 追加
            $table->date('task_limited_at')->nullable()->default(null);  // 追加
            $table->tinyInteger('task_status');  // 追加
            $table->timestamps();
        });
    }

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

こんな感じになります。
では、早速migrationを実行しましょう。
*実行の前に.envにいかがあることを確認しましょう。
*ローカルなので、DBの設定は雑ですw

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=todo_db
DB_USERNAME=root
DB_PASSWORD=

➜  todo_list git:(master) ✗ php artisan migrate
Migrating: 2021_12_20_073530_create_todos_table
Migrated:  2021_12_20_073530_create_todos_table (14.48ms)

上記のようになれば成功です。

あることを確認

mysqlのコンソールであることを確認します。

mysql> use todo_db
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------------+
| Tables_in_todo_db      |
+------------------------+
| failed_jobs            |
| migrations             |
| password_resets        |
| personal_access_tokens |
| todos                  |
| users                  |
+------------------------+
6 rows in set (0.00 sec)

mysql> desc todos;
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int unsigned | NO   | PRI | NULL    | auto_increment |
| task            | varchar(255) | NO   |     | NULL    |                |
| task_limited_at | date         | YES  |     | NULL    |                |
| task_status     | tinyint      | NO   |     | NULL    |                |
| created_at      | timestamp    | YES  |     | NULL    |                |
| updated_at      | timestamp    | YES  |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)

実際のmodel,view,controllerの作成

では、ここからmodel,view,controllerを作っていきます。

model作成

php artisan make:model Todo

コントローラ作成

php artisan make:controller TodolistFormController

routesの作成

これは画面表示のURLになります

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// Route::get('/', function () {
//     return view('welcome');
// });

Route::get('/', 'App\Http\Controllers\TodolistFormController@index');

status

statusはconfigの下に定義します。
laravelはdefaultは、こういう定義系はconfigに置きます。
*使い方は様々なので、自分たちにあった使い方をすればいいかなと思います

<?php

return [

  'task_status' => [
    '未着手',
    '対応中',
    '保留',
    '完了',
    '途中終了',
  ],
];

view

artisanコマンドはないので、自力で作成します

todo_list.blade.php

<h1>ToDo List</h1>
<div>
    <h2>タスクの一覧</h2>
    <a href="/create-page">タスクを追加</a>
    <table border="1">
        <tr>
            <th>タスクの内容</th>
            <th>タスクの期限</th>
            <th>タスクのstatus</th>
            <th colspan="2">操作</th>
        </tr>
        @foreach($todos as $todo)
        <tr>
            <td>{{$todo->task}}</td>
            <td>{{$todo->task_limited_at}}</td>
            <td>{{Config::get('status.task_status')[$todo->task_status]}}</td>
            <td><a href="/edit-page/{{$todo->id}}">編集</a></td>
            <td><a href="/delete-page/{{$todo->id}}">削除</a></td>
        </tr>
        @endforeach
    </table>
</div>

ここまでで

一回動かしてみましょう。

php artisan serve

を叩いて起動するか確認。

builtinサーバが起動したら、上のコマンドを叩いた際に出てきたURLを叩いてみて、表示されるか確認してみる

投稿ページを作成

コントローラとviewをそれぞれ以下で用意します。

以下メソッドを追加してください

// タスク作成画面を表示
    public function createPage()
    {
        return view('todo_create');
    }

    // タスクを登録
    public function create(Request $request)
    {
        $todo = new Todo();
        $todo->task = $request->task;
        $todo->task_limited_at = $request->task_limited_at;
        $todo->task_status = STATUS_BEGIN;

        $todo->save();

        ret

todo_create.blade.php

<h1>ToDo List</h1>
<div>
    <h2>タスクを追加</h2>
    <form method="POST" action="/create">
        @csrf
        <p>
            タスク:<input type="text" name="task">
        </p>
        <p>
            タスクの期限:<input type="text" name="task_limited_at">
        </p>
        <input type="submit" name="create" value="追加">
    </form>
    <a href="/">戻る</a>
</div>

編集と削除

続いて、編集と削除をやってきます。

こっちがcontroller

// タスク編集画面を表示
    public function editPage($id)
    {
        $todo = Todo::find($id);
        return view('todo_edit', [
            "todo" => $todo
        ]);
    }

    // タスクを更新
    public function edit(Request $request)
    {
        Todo::find($request->id)->update([
            'task' => $request->task,
            'task_limited_at' => $request->task_limited_at,

        ]);
        return redirect('/');
    }

こっちがview

<h1>ToDo List</h1>
<div>
    <h2>タスクの修正</h2>
    <form method="POST" action="/edit">
        @csrf
        <input type="hidden" name="id" value="{{$todo->id}}">
        <p>
            タスク:<input type="text" name="task" value="{{$todo->task}}">
        </p>
         <p>
         タスクの期限:<input type="text" name="task_limited_at" value="{{$todo->task_limited_at}}">
         </p>
         <input type="submit" name="edit" value="修正">
     </form>
     <a href="/">戻る</a>
 </div>

削除

routeはこちら

Route::get('/delete-page/{id}', 'App\Http\Controllers\TodolistFormController@deletePage');
Route::post('/delete/{id}', 'App\Http\Controllers\TodolistFormController@delete');

controller

// タスク削除画面を表示
    public function deletePage($id)
    {
        $todo = Todo::find($id);
        return view('todo_delete', [
            "todo" => $todo
        ]);
    }


    // タスクを削除
    public function delete(Request $id)
    {
        Todo::find($id)->delete();
        return redirect('/');
    }

view

<h1>ToDo List</h1>
<div>
    <h2>タスクを削除</h2>
    <form method="POST" action="/delete/{{$todo->id}}">
        @csrf
        <p>
            タスクの名前:{{$todo->task}}
        </p>
        <p>
            タスクの期限:{{$todo->task_limited_at}}
        </p>

        <input type="submit" name="delete" value="削除">
    </form>
    <a href="/">戻る</a>
</div>

これでうまくいくはずです。

その他

余力がある人は、ステータスの変更や、ステータスでの絞り込み機能追加などをやってみると理解が深まると思います。

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