こんにちは。Web系エンジニアのカズです。
今回は初心者の方に向けて、Laravelの更新処理ができるように記事投稿ページを例にして解説していきます。
それぞれのファイルの処理を掲載しているので、全体の処理の流れを掴んでもらいやすいと思います。
ちなみに新規登録処理はこちらで解説しています。
以下の流れで説明。
1.ルーティングファイルの設定
2.テーブル作成
3.モデル作成
4.Bladeファイルの作成
5.controllerの作成
・web.php(ルーティングファイル)
・create_posts_table(テーブル生成に必要なmigrationファイル)
・Post.php(モデルファイル)
・index.blade.php(記事一覧ファイル)
・edit.blade.php(記事更新/編集ファイル)
・PostController.php(登録処理や更新処理などロジックを記載するファイル)
1.ルーティングファイルの設定
web.phpに下記を記載します。
Route::get('/post/index', [PostController::class, 'index'])->name('post.index');
Route::get('/post/register', [PostController::class, 'register'])->name('post.register');
Route::get('/post/edit', [PostController::class, 'edit'])->name('post.edit');
Route::post('/post/update', [PostController::class, 'update'])->name('post.update');
controllerの命名は記事を「投稿する」の意味合いをもつpostにしました。
2.テーブル作成
コマンドでmigrationファイルを作成
php artisan make:migration create_posts_table
これでcreate_posts_tableが生成されます。
そのファイルを開いて編集します。
今回は「記事タイトル」と「記事サブタイトル」と「記事本文」のカラムを設定します。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table)
{
$table->id();
$table->string('title');
$table->string('subtitle')->nullable();
$table->text('text')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
migrationファイルが編集出来たら、migrate実行をしてテーブル生成をします。
php artisan migrate
テーブル生成されました。
おすすめ本
3.モデル作成
php artisan make:model Post
生成されたPost.phpを編集します。
$guardedで登録する対象カラムの定義を記載します。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post;
class Post extends Model
{
use HasFactory;
protected $guarded = [
'id',
];
public function post() {
return Post::get();
}
}
$guardedの中にidを定義することでid以外のカラムを対象としています。
保存する処理のcreateやsaveメソッドを使う際に、こちらの定義が関係します。
$guardedではなく$fillableで記載する方法もありますが、全ての対象カラムを記載する手間があるため$guardedを使用しています。
4.Bladeファイルの作成
一覧画面のbladeファイル
<h1>記事一覧</h1>
<a href="register">新規登録</a>
<table border="1" cellspacing="0">
<tr>
<th>ID</th>
<th>タイトル</th>
<th>サブタイトル</th>
<th>本文</th>
</tr>
@foreach($posts as $post)
<tr onclick="trClick( {{$post->id}} );">
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->text}}</td>
</tr>
@endforeach
</table>
<style>
tr:hover {
background-color : #CCFFFF; /*マウスが乗ったら背景色を変更する*/
cursor : pointer; /*マウスが乗ったらポインターを変更する*/
}
</style>
<script>
function trClick(id) {
location.href = 'edit?id='+id;
}
</script>
</html>
controllerから渡してきた$postsの変数を使用しています。
$postsはデータベースに保存されているデータを取得します。
$postを使用してカラムごとにデータを表示しています。
クリックした行のデータのidをパラメータとして渡して画面遷移させます。
遷移先は編集画面で処理的にはcontrollerのedit関数に処理が移ります。
更新/編集画面のbladeファイル
<h1>編集</h1>
<form action="update" method="POST">
@csrf
<p>タイトル</p>
<input type="text" name="title" value="{{$post->title}}" maxlength="30"/>
<br/>
<p>サブタイトル</p>
<input type="text" name="subtitle" value="{{$post->subtitle}}" maxlength="30"/>
<br/>
<p>本文</p>
<textarea name="text" maxlength="300">{{$post->text}}</textarea>
<br/>
<input type="hidden" name="id" value="{{$post->id}}">
<input type="submit" value="登録" />
</form>
$postをcontrollerのedit関数からパラメータで受け取っています。
$postにidで絞り込まれたデータ1件が配列で格納されており、それぞれのカラムに値をセットしています。
登録ボタンを押下すると、controllerのupdate関数に処理が移り
更新処理が実行されます。
また実際の画面のレイアウトについては、CSSは特に何も加工していません。
5.controllerの作成
コントローラーを生成
php artisan make:controller PostController
コントローラーを生成したら編集
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index(Request $request)
{
$posts = Post::post();
return view('post.index', [
'posts' => $posts
]);
}
public function edit(Request $request)
{
$post = Post::find($request->id);
return view('post.edit', [
'post' => $post
]);
}
public function update(Request $request) {
try {
$posts = Post::post();
Post::where('id', $request->id)->update([
'title' => $request->title,
'subtitle' => $request->subtitle,
'text' => $request->text,
]);
return redirect()->route('post.index')->with([
'posts' => $posts,
'update' => 'true'
]);
} catch (Exception $e) {
return redirect()->route('post.index')->with([
'posts' => $posts,
'update' => 'false'
]);
}
}
}
edit関数の$request->idには一覧画面でクリックしたレコードのidが渡ってきます。
そのidと一致するデータ1件をデータベースから抽出した$postの変数をパラメータとしてedit.blade.phpに渡します。
update関数でデータベースに更新する処理があります。
登録が正常にできれば、一覧画面にリダイレクトされてパラメータのupdateにtrueが渡ります。
今回は実装していませんが、更新が完了したらアラートを出すこともパラメータを使用して実現できます。
コメント