Laravel9 Eloquent ORM

ORM stands for Object Relational Model
When using eloquent, each database table has corresponding Model.
Model is used to interact with the database table.

Create new model using artisan command

php artian make:model Post


Migration is like version control for your database, where we define the schema of the database.
using migration we can easy add, remove and change the type of the table in the database.

Create model and migration together

php artisan make:model Post --migration or -m

Generate model, migration, factory, seeder, and controller

php artisan make:model Post -mfsc

Generate migration individually

php artisan make:migration create_posts_table
Migration class has two basic method up and down.
Schema::create('flights', function (Blueprint $table) {

public function down()

Run migrations

php artisan migrate

To check migration status

php artisan migrate:status
This will show which migration are ran and which one are pending.
To see complete sql query for migration which is in pending without executing to the database
php artisan migrate --pretend

Rollback the last *batch of migration      

php artisan migrate:rollback

Rollback last n migrations

php artisan migrate:rollback --step=3

Rollback all the migrations

php artisan migrate:reset

Rollback all the migration and recreate all the migrations again

php artisan migrate:refresh

Refresh all the migrations and seed again

php artisan migrate:refresh --seed

Mostly used column types

$table->char("name", 100);
$table->decimal('amount', $precision = 8, $scale = 2);
$table->double('amount', 8, 2);
$table->enum('difficulty', ['easy', 'hard']);
UNSIGNED BIGINT equivalent column.

Column modifiers


Foreign key constraints

Schema::table('posts', function (Blueprint $table) {

use delete, update cascade

column modifiers can be used with foreignId but before the the constrained method.

Seeding database

Laravel includes ability to seed database with fake data.
By default DatabaseSeeder class is set, from here we can call the method "call" to other seed classes.

Create new seeder

php artisan make:seeder UserSeeder
Seeder class contain one method that is run, and this method called automatically when we use db:seed.


To generate some fake data for testing.
public function definition(){
  return [
      'name' => fake()->name(),
      'email' => fake()->safeEmail(),
      'email_verified_at' => now(),
      'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
      'remember_token' => Str::random(10),

At Seeder class

use App\Models\User;
class UserSeeder extends Seeder
   * Run the database seeds.
   * @return void
  public function run()
© 2016 - 2022, All Rights are Reserved.