Defining Models and Migrations
Every Eloquent model needs a matching database table to represent, and Laravel uses migrations to define that structure in code. Together, models and migrations form the backbone of how a Laravel application manages its data layer.
What Is a Model?
A model is a PHP class, usually generated through Artisan, that represents a single database table. By convention, Laravel assumes a model named Post corresponds to a table named posts, though this can be overridden when needed.
What Is a Migration?
A migration is a version-controlled PHP file that describes changes to the database schema, such as creating a table or adding a column. Because migrations live alongside application code, the entire team can stay in sync on the database structure without manually running SQL scripts.
| File Type | Purpose |
|---|---|
| Model | Represents and interacts with a database table in PHP |
| Migration | Defines or modifies the actual table structure |
| Factory | Generates fake data for testing based on a model |
| Seeder | Populates the database with initial or sample records |
Generating Both Together
- Artisan can generate a model and its migration in a single command
- Column definitions live inside the migration's
up()method - Model properties like
$fillablecontrol which fields can be mass-assigned
With a model and its matching table structure in place, the model is finally ready to actually store and retrieve data — starting with the basic CRUD operations covered next.
Generating a Model and Migration Together
Artisan can create the model, its migration, a factory and a seeder in one command. The -m flag adds the migration, -f the factory and -s the seeder:
php artisan make:model Post -mfs
This creates app/Models/Post.php, a timestamped file in database/migrations, plus matching factory and seeder classes. Open the migration and describe the table inside up():
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->string('slug')->unique();
$table->text('body');
$table->boolean('is_published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};
foreignId('user_id')->constrained() creates the column and a foreign key to the users table in one line. The down() method reverses the change, which is what makes rollbacks possible.
Preparing the Model Class
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = ['title', 'slug', 'body', 'is_published', 'published_at'];
protected function casts(): array
{
return [
'is_published' => 'boolean',
'published_at' => 'datetime',
];
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Casts turn raw database values into proper PHP types, so $post->published_at becomes a date object you can format. Older projects define casts as a $casts property, which still works.
Running and Changing Migrations Safely
| Command | What it does |
|---|---|
php artisan migrate | Runs every migration that has not run yet |
php artisan migrate:status | Shows which migrations have run |
php artisan migrate:rollback | Reverses the last batch using each down() method |
php artisan migrate:fresh --seed | Drops all tables, rebuilds them and seeds data; local development only |
To change a table that already exists, create a new migration instead of editing the old one:
php artisan make:migration add_views_to_posts_table --table=posts
Mistakes New Laravel Developers Make
- Editing a migration that has already run on a shared or production database; other environments will never pick up the change.
- Leaving
down()empty, which makes rollbacks impossible. - Using
$guarded = []everywhere, which allows any field to be mass-assigned from user input. - Naming models in plural, which breaks Laravel's table-name convention; keep models singular and tables plural.
- Running
migrate:freshagainst the wrong.envand wiping real data.
Filling the Table with Factory Data
Once the table exists, the factory generated earlier makes realistic sample rows for development and tests. Inside the factory's definition() method, return an array that uses the built-in Faker helper, for example a sentence for the title, a unique slug and a few paragraphs for the body. Then call it from the seeder or from a test:
Post::factory()->count(20)->create();
Because the factory knows about the model, every generated row passes through the same casts and relationships your application uses. That makes demo pages look real and lets feature tests start from a known, repeatable state. Keep factories close to real-world data shapes, such as long titles or empty optional fields, so they expose layout and validation bugs early.
A good routine for every new table is: generate the model with its migration, define columns and foreign keys, write a matching down(), set $fillable and casts, add the relationships, and finally create a factory so the table can be filled with one line.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.