How to use Eloquent Model in Laravel Migration
In this lesson, we will see how to use the eloquent model in Laravel migration, let's assume that we are migrating a contacts table, and at the same time we want to insert some messages into the table.
Use Eloquent Model in Laravel Migration
To do that we call the create method inside our migration see the example below:
<?php
use App\Models\Contact;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->text('message');
$table->timestamps();
});
Contact::create(['name' => 'John', 'email' => 'john@email.com', 'message' => 'hello there']);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contacts');
}
};