#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

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 TypePurpose
ModelRepresents and interacts with a database table in PHP
MigrationDefines or modifies the actual table structure
FactoryGenerates fake data for testing based on a model
SeederPopulates the database with initial or sample records

Generating Both Together

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

CommandWhat it does
php artisan migrateRuns every migration that has not run yet
php artisan migrate:statusShows which migrations have run
php artisan migrate:rollbackReverses the last batch using each down() method
php artisan migrate:fresh --seedDrops 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:fresh against the wrong .env and 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.

Explore Course