WEB アプリケーションには、CRUD という機能をつけると良いとされています。 CRUD とは、Create (作成)、Read (読み込み)、Update (更新)、Delete (削除)の頭文字をとったものです。 今回は、Create (作成) 機能をつけていきます。
resources / views / index.blade.php を次のように書きかえてください。
途中に出てくる h-layout は、x-layout から名前を変更したものです。注意してください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task</title>
<link rel="stylesheet" href="{{ url('style.css') }}">
</head>
<body>
<div class="container">
<h1>Task</h1>
<!-- ここから -->
<form method="POST" action="{{ route('tasks.store')}}">
@csrf
<div class="h-layout">
<input type="text" name="body"><button class="btn-black">Create</button>
</div>
</form>
<p class="error">
@error('body')
{{ $message }}
@enderror<br></p>
<!-- ここまで増えています -->
@forelse ($tasks as $task)
<p class="task">{{ $task->body }}</p>
@empty
<p class="task">No task!</p>
@endforelse
</ul>
</div>
</body>
</html>
app / Http / Controllers の TaskController.php に store メソッドを追加します。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Task;
class TaskController extends Controller
{
public function index()
{
$tasks = Task::all();
return view('index')->with(['tasks' => $tasks]);
}
// ここから
public function store(Request $request)
{
$request->validate([
'body'=>'required|max:30',
]);
$task = new Task();
$task->body = $request->body;
$task->save();
return redirect()->route('tasks.index');
}
// ここまで追加します
}
インデックスページの表示を整えるため、public フォルダに、次のファイルを style.css というファイル名で作ってください。
途中に出てくる h-layout は、x-layout から名前を変更したものです。注意してください。
body { background-color: #efefef; } .container { width: 500px; margin: 16px auto; } h1 { font-size: 20px; } .task { height: 80px; width: 100%; border-radius: 4px; padding: 0px 8px; line-height: 80px; box-sizing: border-box; background-color: white; margin-bottom: 0px; } /* ここから */ .h-layout { display: flex; } input { height: 25px; width: 100%; padding: 4px; border: solid 0px #efefef; border-radius: 4px; } .btn-black { background-color: black; width: 60px; color: white; border-radius: 4px; } .error { margin-bottom: 0px; color: red; font-size: xx-small; } /* ここまで追加します */
php artisan serve で Task アプリを起動して、localhost:8000 で確認してください。