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

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) {
          $table->id();
          $table->string('name');
          $table->string('airline');
          $table->timestamps();
        });

public function down()
  {
      Schema::drop('flights');
    }

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->bigIncrements("id");
$table->bigInteger("votes");
$table->boolean("confirmed");
$table->char("name", 100);
$table->date("created_at");
$table->decimal('amount', $precision = 8, $scale = 2);
$table->double('amount', 8, 2);
$table->enum('difficulty', ['easy', 'hard']);
$table->foreignId('user_id'); 
UNSIGNED BIGINT equivalent column.
 
$table->longText('description');

Column modifiers

->nullable();
->default("active");
->unique();

Foreign key constraints

Schema::table('posts', function (Blueprint $table) {
  $table->unsignedBigInteger('user_id');
  $table->foreign('user_id')->references('id')->on('users');
  or 
  $table->foreignId('user_id')->constrained('users');
});

use delete, update cascade

 $table
->foreignId('user_id')
->constrained('users')
->onUpdate("cascade")
 ->onDelete("cascade");
 
column modifiers can be used with foreignId but before the the constrained method.
 
 $table
->foreignId('user_id')
->nullable()
 ->constrained('users')

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.
 

Factory

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()
  {
      User::factory(10)->create();
  }
}
© 2016 - 2022, All Rights are Reserved.