Advertisement

Google Ad Slot: content-top

Laravel Eloquent ORM (Object Relational Mapping)


What is Eloquent ORM?

  • Eloquent is Laravel’s built-in Object-Relational Mapping (ORM) that allows you to interact with your database tables using PHP classes and expressive syntax.
  • Each model in Eloquent represents a table in the database.
  • Each row in the table is an object of that model.

Defining a Model

Generate a model with Artisan:

php artisan make:model Post


This generates a file in app/Models/:

By default:

  • Post model → posts table
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Basic Usage

class Post extends Model
{    
    protected $fillable = ['title', 'content', 'is_published', 'published_at'];
}


Mass assigned

Use $fillable to define mass-assignable fields:

protected $fillable = ['title', 'content'];

(OR)

protected $guarded = [];

to block mass assignment for specific fields.