0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel CRUDについて

Posted at

はじめに

アプリケーションを作る際に基本的な機能となるCRUDを説明していく。

CRUDとは

CRUDとは、下記のステップの頭文字をとったもの。

Create 作成
Read 読み出し
Update 更新
Delete 削除

CRUDとは、データを使ったシステムで共通して行う4つの処理を表現した言葉を言う。

LaravelでCRUDを作成する

LaravelではリソースコントローラというCRUDを簡単に作成することができる機能をもっています。
CRUDの処理はコントローラーに記述していくことになりますが、下記コマンドでまとめて作成することができます。

php artisan make:controller TestController –resource

上記コマンドを打ち込むことで一般的にWEBアプリケーションを作成する上で必要となってくる7つのアクションメソッドを自動で作成することができます。

作成されるメソッド
index 一覧表示
create 作成
store 作成したものを保存
show 個別ページ
edit 編集
update 編集したものを保存
destroy 削除

といったような7つのメソッドを自動で作成してくれます。

ルートを設定する

LaravelだけでなくWEBアプリケーションを作成するうえでほぼ必ずルーティング設定をすることになります。
一般的にリソースコントローラを使わずにルート設定をする場合下記のような感じで記述することとなります。
※バージョンによって書き方が違うため、公式を確認するようお願いします

web.php
// 一覧
Route::get('post', [PostController::class, 'index']);
// 作成
Route::get('post/create', [PostController::class, 'create']);
// 保存
Route::post('post', [PostController::class, 'store']);
// 表示
Route::get('post/{post_id}', [PostController::class, 'show']);
// 編集
Route::get('post/edit/{post_id}', [PostController::class, 'edit']);
// 更新
Route::put('post/{post_id}', [PostController::class, 'update']);
// 削除
Route::delete('post/{post_id}', [PostController::class, 'destroy']);

これをリソースコントローラで書くと下記一文で済んでしまいます。

web.php
Route::resource('posts', PostController::class);

非常に楽ですね。

ただメソッド名を変えたい場合などはこのような書き方ではかけないため、1つずつルート指定をしてあげる必要があります。
場合によって適宜変えていきましょう。

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?