はじめに
こんにちは、Webエンジニアの岩田史門(@SI_Monxy)です!
今回はLaravelとMySQLを使ったCRUDアプリケーションの作り方について記事を書いてみました!
改善点や修正点があれば、コメントにてやさしくご指導いただけると嬉しいです!
概要
この記事では、LaravelとMySQLを使用してCRUD(Create, Read, Update, Delete)機能を備えたウェブアプリケーションを構築する方法について説明します。LaravelはPHPで書かれた人気のあるフレームワークであり、MySQLは広く使用されているリレーショナルデータベース管理システムです。
環境の準備
まずはじめに、Laravelプロジェクトをセットアップし、MySQLデータベースに接続する必要があります。以下の手順に従って進めてください。
Laravelプロジェクトの作成
laravel new crud-app
cd crud-app
MySQLデータベースの設定
.envファイルでMySQLの設定を行います。
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
データベースマイグレーション
マイグレーションを使用してデータベーステーブルを作成します。
php artisan migrate
CRUD機能の実装
次に、CRUD機能を実装します。以下に各操作に対する基本的な手順とサンプルコードを示します。
データの作成 (Create)
新しいデータを作成するためのフォームと処理を作成します。
フォームの表示(resources/views/create.blade.php)
<form method="POST" action="{{ route('items.store') }}">
@csrf
<input type="text" name="name" placeholder="商品名">
<button type="submit">作成</button>
</form>
コントローラの処理(app/Http/Controllers/ItemController.php)
public function store(Request $request)
{
Item::create([
'name' => $request->input('name')
]);
return redirect()->route('items.index');
}
データの表示 (Read)
データを取得して表示する処理を実装します。
ビュー(resources/views/index.blade.php)
@foreach ($items as $item)
<p>{{ $item->name }}</p>
@endforeach
コントローラの処理(app/Http/Controllers/ItemController.php)
public function index()
{
$items = Item::all();
return view('index', compact('items'));
}
データの更新 (Update)
既存のデータを更新するためのフォームと処理を作成します。
フォームの表示(resources/views/edit.blade.php)
<form method="POST" action="{{ route('items.update', $item->id) }}">
@csrf
@method('PUT')
<input type="text" name="name" value="{{ $item->name }}">
<button type="submit">更新</button>
</form>
コントローラの処理(app/Http/Controllers/ItemController.php)
public function update(Request $request, $id)
{
$item = Item::findOrFail($id);
$item->update([
'name' => $request->input('name')
]);
return redirect()->route('items.index');
}
データの削除 (Delete)
データを削除する処理を実装します。
削除ボタンの設置(resources/views/index.blade.php)
<form method="POST" action="{{ route('items.destroy', $item->id) }}">
@csrf
@method('DELETE')
<button type="submit">削除</button>
</form>
コントローラの処理(app/Http/Controllers/ItemController.php)
public function destroy($id)
{
$item = Item::findOrFail($id);
$item->delete();
return redirect()->route('items.index');
}
まとめ
以上で、LaravelとMySQLを使用してCRUD機能を持つ基本的なウェブアプリケーションを作成する方法について説明しました。これにより、データの作成、読み取り、更新、削除といった基本的な操作を実行することができます。