この記事で解決できる悩み

こんな悩みを解決できる記事を書きました!
僕は現役フリーランスエンジニア(歴9年)で、資格は13個保有しています。
「LaravelのマイグレーションでViewを作成する方法を知りたい」とお考えではありませんか?
結論からお伝えすると、マイグレーションでViewを作成する方法は超簡単です。



テーブルを作成する時とほぼ変わらないので簡単ですよ。
ということで、本記事ではLaravelのマイグレーションでViewを作成する方法を解説します。





すぐ読み終わるので、ぜひ最後まで読んでくださいませ。
目次
【Laravel】マイグレーションでViewを作成する方法
早速ですが、LaravelのマイグレーションでViewを作成する方法を解説します。
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class CreateSampleView extends Migration
{
public function up()
{
DB::statement("
CREATE VIEW sample_view AS
SELECT
users.id,
users.name,
users.email
FROM users
WHERE users.deleted_at IS NULL
");
}
public function down()
{
DB::statement("DROP VIEW IF EXISTS sample_view");
}
}
上記のように、直接SQLを実行すればOKです。



Laravel標準のSchemaビルダーにはビュー専用のメソッドは用意されていません。
なので、生SQLを実行してビューを作成・削除する必要があります。
まとめ
今回は、LaravelのマイグレーションでViewを作成する方法について解説しました。
以下が本記事のまとめになります。
- おすすめ本
Laravelの勉強なら「PHPフレームワーク Laravel入門 第2版



最後までお読みいただき、ありがとうございました!
- クソおすすめ本



海外のエンジニアがどういった思考で働いているかが理解できます。
海外に行く気はないけど海外エンジニアの動向が気になる雑魚エンジニアにおすすめです(本当におすすめな本しか紹介しないのでご安心を)。