Developer Snippet Diary

How to Use Laravel Migrations for Efficient Database Management

Migrations (structure of table ), create tables in phpmyadmin auto using structure

Laravel migrations are a database version control system built into the Laravel PHP framework. They allow you to define and modify the structure of your database tables using PHP code, and track changes to the schema over time.

With Laravel migrations, you can create new tables, modify existing tables, and even add new columns or indexes to tables that are already in use.

When you run a migration, Laravel will apply the changes defined in the migration file to your database. You can also roll back migrations, which will undo the changes made by a particular migration. This makes it easy to test and modify your database schema over time, without worrying about losing data or having to manually update your database structure.

every table should has its own model

create migration with model, use singular model name laravel make it auto plural

php artisan make:model Customer -m

it will create an model inside http>models and migration inside database>migrations

Now edit customer migration as 

 public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            		$table->id(); //primary key
			$table->string('name');
			$table->string('email')->unique();
			$table->string('address')->nullable(); //optional
			$table->string('phone');
            		$table->timestamps(); //created_at and updated_at column
        });
    }

run migtation, it will create all tables that are defined in migrations

php artisan migrate

To delete last create table

php artisan migrate:rollback --step=1

To modify migration use below commands

php artisan migrate:reset
php artisan migrate
Posted by: R GONDAL
Email: rizikmw@gmail.com