Laravel Eloquent ORM Cheatsheet

1. Basic CRUD Operations

// Retrieving All Rows
$users = User::all();

// Retrieving a Single Row by ID
$user = User::find(1);

// Creating a New Record
$user = new User();
$user->name = 'John Doe';
$user->save();

// Updating an Existing Record
$user = User::find(1);
$user->name = 'Jane Doe';
$user->save();

// Deleting a Record
User::destroy(1);

2. Querying Data

// Retrieving Rows with Conditions
$users = User::where('status', 'active')->get();

// Ordering Results
$users = User::orderBy('name', 'asc')->get();

// Pagination
$users = User::paginate(10);

// Chunking Results
User::chunk(100, function($users) {
  foreach ($users as $user) {
    // Process each user
  }
});

3. Eloquent Relationships

// One-to-One Relationship
public function profile() {
  return $this->hasOne(Profile::class);
}

// One-to-Many Relationship
public function posts() {
  return $this->hasMany(Post::class);
}

// Many-to-Many Relationship
public function roles() {
  return $this->belongsToMany(Role::class);
}

// Defining Inverse Relationships
public function user() {
  return $this->belongsTo(User::class);
}

// Polymorphic Relationships
public function imageable() {
  return $this->morphTo();
}

4. Query Scopes

// Global Scope
protected static function boot() {
  parent::boot();
  static::addGlobalScope('active', function (Builder $builder) {
    $builder->where('status', 'active');
  });
}

// Local Scope
public function scopeActive($query) {
  return $query->where('status', 'active');
}

// Using Local Scope
$users = User::active()->get();

5. Mutators & Accessors

// Accessor for Full Name
public function getFullNameAttribute() {
  return $this->first_name . ' ' . $this->last_name;
}

// Mutator for Setting Name
public function setNameAttribute($value) {
  $this->attributes['name'] = strtolower($value);
}

// Using Accessors & Mutators
$user = User::find(1);
echo $user->full_name; // Accessor
$user->name = 'John Doe'; // Mutator

6. Soft Deletes

// Enabling Soft Deletes
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
  use SoftDeletes;
  protected $dates = ['deleted_at'];
}

// Soft Deleting a Record
User::find(1)->delete();

// Restoring a Soft Deleted Record
User::withTrashed()->find(1)->restore();

// Permanently Deleting a Record
User::withTrashed()->find(1)->forceDelete();

7. Timestamps

// Automatic Timestamps
User::create(['name' => 'John Doe']);
// Will automatically fill created_at and updated_at

// Disabling Timestamps
public $timestamps = false;

// Updating Timestamps Manually
$user = User::find(1);
$user->timestamps = false;
$user->save();

8. Eager Loading

// Eager Loading Relationships
$users = User::with('profile', 'posts')->get();

// Eager Loading Nested Relationships
$users = User::with(['posts.comments'])->get();

// Lazy Eager Loading
$users = User::all();
$users->load('posts');

9. Casting Attributes

// Defining Attribute Casting
protected $casts = [
  'is_admin' => 'boolean',
  'created_at' => 'datetime:Y-m-d',
];

// Using Casts
$user = User::find(1);
echo $user->is_admin ? 'Admin' : 'User';

10. Mass Assignment

// Guarded Attributes
protected $guarded = ['id'];

// Fillable Attributes
protected $fillable = ['name', 'email'];

// Mass Assignment Example
User::create(['name' => 'John Doe', 'email' => 'john@example.com']);

11. Events & Observers

// Creating an Observer
php artisan make:observer UserObserver --model=User

// Defining Observer Methods
public function creating(User $user) {
  $user->name = strtoupper($user->name);
}

// Registering the Observer
User::observe(UserObserver::class);

// Model Events
User::created(function($user) {
  Mail::to($user->email)->send(new WelcomeEmail($user));
});

12. Tips & Tricks

// Incrementing or Decrementing Columns
User::find(1)->increment('points');
User::find(1)->decrement('points', 5);

// Using FirstOrCreate
$user = User::firstOrCreate(['email' => 'john@example.com'], ['name' => 'John Doe']);

// Updating or Creating a Record
$user = User::updateOrCreate(['email' => 'john@example.com'], ['name' => 'John Doe']);

// Using WhereHas for Filtering Related Models
$users = User::whereHas('posts', function ($query) {
  $query->where('status', 'published');
})->get();

// Lazy Updates to Avoid Saving Unchanged Data
$user = User::find(1);
$user->name = 'New Name';
if ($user->isDirty()) { // Check if changes are made
  $user->save();
}

// Using Chunking to Process Large Datasets
User::chunk(100, function ($users) {
  foreach ($users as $user) {
    // Process each user
  }
});

// Using pluck() for Extracting Specific Values
$names = User::pluck('name'); // Extract the 'name' column

// Using withCount to Get Related Model Count
$users = User::withCount('posts')->get(); // Returns users along with posts_count

// Safely Deleting Relationships (Cascading Deletes)
class User extends Model {
  protected static function boot() {
    parent::boot();
    static::deleting(function ($user) {
      $user->posts()->delete();
    });
  }
}

// Avoiding N+1 Query Problem with Eager Loading
$users = User::with('posts')->get();

// Using touch() to Update Timestamps on Related Models
$user = User::find(1);
$user->posts()->touch(); // Updates the updated_at timestamps of related posts

// Setting Default Values for Attributes
protected $attributes = [
  'status' => 'active',
];

// Using Exists to Check if a Record Exists
if (User::where('email', 'john@example.com')->exists()) {
  // User with this email exists
}

// Using select() for More Efficient Queries
$users = User::select('name', 'email')->get(); // Retrieve only specific columns

// Getting Random Rows
$randomUser = User::inRandomOrder()->first();

// Batch Updates
User::where('status', 'inactive')->update(['status' => 'active']);

// Accessing Pivot Table Data in Many-to-Many Relationships
$role = Role::find(1);
foreach ($role->users as $user) {
  echo $user->pivot->created_at; // Accessing pivot table columns
}

// Raw Queries within Eloquent
$users = User::whereRaw('DATE(created_at) = CURDATE()')->get();

// Using FindOrFail to Throw 404 if Not Found
$user = User::findOrFail($id); // Throws a 404 if the user is not found

// Using firstOrFail for Queries
$post = Post::where('slug', $slug)->firstOrFail();

// Filtering by Relationship Count
$users = User::has('posts', '>=', 5)->get(); // Users with at least 5 posts

// Loading Multiple Levels of Relationships
$users = User::with(['posts.comments'])->get();

// Soft Deleting with Related Models (Cascading Soft Deletes)
protected static function boot() {
  parent::boot();
  static::deleting(function ($user) {
    if ($user->isForceDeleting()) {
      $user->posts()->forceDelete();
    } else {
      $user->posts()->delete();
    }
  });
}