0
0
LaravelHow-ToBeginner · 3 min read

How to Create Model with Migration in Laravel Easily

Use the php artisan make:model ModelName -m command to create a model along with its migration file in Laravel. This command generates both files so you can define the database structure and the model logic together.
📐

Syntax

The command to create a model with a migration in Laravel is:

  • php artisan make:model ModelName -m

Here:

  • ModelName is the name of your model (usually singular and capitalized).
  • -m flag tells Laravel to create a migration file along with the model.
bash
php artisan make:model ModelName -m
💻

Example

This example creates a Post model and its migration file. The migration defines a table with title and content columns.

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

// Model file: app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'content'];
}
Output
Creates migration file in database/migrations and model file in app/Models/Post.php
⚠️

Common Pitfalls

Common mistakes when creating models with migrations include:

  • Not using the -m flag, which creates only the model without a migration.
  • Forgetting to run php artisan migrate after creating the migration, so the database table is not created.
  • Using plural names for models instead of singular, which breaks Laravel conventions.

Example of wrong and right usage:

bash
// Wrong: creates only model without migration
php artisan make:model Posts

// Right: creates model and migration
php artisan make:model Post -m
📊

Quick Reference

CommandDescription
php artisan make:model ModelNameCreates a model only
php artisan make:model ModelName -mCreates a model with a migration
php artisan migrateRuns all pending migrations to create tables
php artisan migrate:rollbackRolls back the last batch of migrations

Key Takeaways

Use php artisan make:model ModelName -m to create a model with its migration.
Always run php artisan migrate after creating migrations to update the database.
Name models in singular form to follow Laravel conventions.
The migration file defines the database table structure for the model.
Use -m flag to avoid creating migrations separately.