使用Laravel8+Vue3+Bootstrap5實作TODO List網頁應用程式的系列文章第六篇。
本文將介紹一下Web Route,並示範建立待辦事項的網頁。
Web Route的相關設定是在routes/web.php
中管理。
Route::get('/', function () {
$todos = Todo::orderBy('created_at', 'DESC')->get();
return view('welcome', ['todos' => $todos]);
})->name('todos.index');
// Route::get('/', [TodoController::class, 'list'])->name('todos.index');
Route::post('/todo', function(Request $request) {
$newTodo = new Todo();
$newTodo->body = $request->todo_body;
$newTodo->save();
return redirect()->route('todos.index');
})->name('todo.store');
畫面的檔案則是在resources/views/
下可以找到。
以下是修改後的welcome.blade.php
的內容。
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body class="antialiased">
<div>
<!-- 1. title -->
<h2>My Todo List</h2>
<!-- 3. "add todo" form-->
<form action="{{ route('todo.store') }}" method="post">
@csrf
<input type="text" name="todo_body" id="todo_body"
placeholder="Enter your task">
<input type="submit" value="+">
</form>
<!-- 2. todo list -->
<ul>
@foreach ($todos as $key => $todo)
<li>
<span>
{{ $todo->body }}
</span>
</li>
@endforeach
</ul>
</div>
</body>
</html>
由於列表是由形式相同的項目所組合而成,所以可以使用foreach的寫法。
@foreach ($todos as $key => $todo)
<li>
<span>
{{ $todo->body }}
</span>
</li>
@endforeach
注意Form的部分,要特別去做CSRF的設定。也就是@csrf
這一項描述。
Form的action的設定中使用的是route name。
使用route name來取得route path的好處是在日後的開發中,若是路徑有任何變更的話,只要去修改web.php
的設定即可。
而route name的設定是在routes/web.php
中透過使用**name()**函數來指定名稱。
Route::get('/', function () {
$todos = Todo::orderBy('created_at', 'DESC')->get();
return view('welcome', ['todos' => $todos]);
}
)->name('todos.index'); // <-- set route name here.
Laravel8+Vue3+Bootstrap5實作TODO List ep09:安裝bootstrap5並美化todo list畫面
Laravel8+Vue3+Bootstrap5實作TODO List ep07:安裝vue3跟基本設定
Laravel8+Vue3+Bootstrap5實作TODO List ep08:用vue重新製作todo list畫面
Laravel8+Vue3+Bootstrap5實作TODO List ep06:初步認識Web Route
Laravel8+Vue3+Bootstrap5實作TODO List ep05:製作新增、更新、刪除待辦事項的API