Generate a Model from an Existing Migration in Laravel

To auto-create a model from a migration file in Laravel, follow these steps:


1. Generate a Model from an Existing Migration

Run the following command:

php artisan make:model YourModelName

For example, if your table is inventories, run:

php artisan make:model Inventory

2. Generate a Model with a Migration and Factory (if needed)

If you haven’t created a migration yet and want to generate both:

php artisan make:model Inventory -m
  • -m → Creates a migration file (skip this if you already have a migration).
  • -f → Creates a factory for database seeding.
  • -c → Creates a controller.
  • -s → Creates a seeder.
  • -r → Creates a resource controller.

Example:

php artisan make:model Inventory -mfsc

This will create:

  • app/Models/Inventory.php
  • database/migrations/xxxx_xx_xx_xxxxxx_create_inventories_table.php
  • database/factories/InventoryFactory.php
  • database/seeders/InventorySeeder.php
  • app/Http/Controllers/InventoryController.php

3. Define the Model (if generated separately)

After generating the model, open app/Models/Inventory.php and define:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    use HasFactory;

    protected $table = 'inventories'; // Specify table if name is different
    protected $fillable = [
        'subsidiary', 'asset_detail', 'asset_account_id', 'date_of_capital',
        'asset_quantity', 'asset_unit', 'dept_code', 'site_resp', 'room',
        'activity', 'acquisitionvalue', 'bookvalue', 'section_name', 'origin_code'
    ]; // Mass assignable fields

    public $timestamps = false; // Disable timestamps if not in the table
}

4. Auto-Generate Model Using Laravel Model Generator (Optional)

If you want to auto-generate models from the database:

Step 1: Install the package

composer require reliese/laravel

Step 2: Publish the configuration

php artisan vendor:publish --tag=reliese-models

Step 3: Generate models

Run the following command:

php artisan code:models

This will generate models for all tables in app/Models.


Now, you can use the model to interact with the database:

$inventory = Inventory::all(); // Fetch all records

Would you like help with defining relationships in the model? 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *