Master Laravel Eloquent: Essential Model Cheat Sheet & Usage Guide

This cheat sheet provides a concise yet comprehensive guide to Laravel's Eloquent Model, covering definition, artisan commands, common CRUD methods, soft‑deletes, relationship types, model events, and configuration tips, all illustrated with ready‑to‑copy code examples.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Master Laravel Eloquent: Essential Model Cheat Sheet & Usage Guide

Overview

The Laravel Model class is the core of Eloquent ORM, representing database tables and providing an expressive, object‑oriented way to perform CRUD operations. Most Model methods mirror those of the underlying DB class, but with a simpler syntax.

Basic Usage

// Define a basic Eloquent model
class User extends Model {}

// Generate a model via Artisan
php artisan make:model User

// Generate a model and its migration file
php artisan make:model User --migration   // or -m

// Generate a model, migration, and a controller (or resource controller)
php artisan make:model User -mc[r]

// Specify a custom table name
class User extends Model {
    protected $table = 'my_users';
}

Common Model Methods

Model::create(['key' => 'value']);
Model::firstOrCreate(['key' => 'value']);
Model::firstOrNew(['key' => 'value']);
Model::updateOrCreate(['search_key' => 'search_value'], ['key' => 'value']);
Model::fill($attributes); // beware of mass‑assignment security
Model::destroy(1);
Model::all();
Model::find(1);
Model::find([ 'first', 'last' ]); // composite primary key
Model::findOrFail(1);
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
Model::where('foo', '=', 'bar')->exists();
Model::whereFoo('bar')->first(); // dynamic attribute
Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
Model::where('foo', '=', 'bar')->toSql(); // raw query string
Model::whereRaw('foo = bar and cars = 2', [20])->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);
Model::all()->orderBy('column');
Model::all()->orderBy('column', 'desc');
// JSON queries
Model::where('options->language', 'en')->get();
Model::whereJsonContains('options->languages', 'en')->get();
Model::whereJsonLength('options->languages', 0)->get();
Model::whereJsonDoesntContain('options->languages', 'en')->get();

Soft Deletes

Model::withTrashed()->where('cars', 2)->get(); // include soft‑deleted rows
Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete(); // permanent delete
Model::onlyTrashed()->where('cars', 2)->get(); // only soft‑deleted rows

Relationships

// One‑to‑One
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
return $this->belongsTo('App\User', 'foreign_key', 'other_key');

// One‑to‑Many
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');

// Many‑to‑Many
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
return $this->belongsToMany('App\User'); // inverse
// Access pivot columns
$role->pivot->created_at;
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
return $this->belongsToMany('App\Role')->withTimestamps();

// Has‑Many‑Through (far‑through)
return $this->hasManyThrough('App\Post', 'App\User', 'country_id', 'user_id');

// Polymorphic (morph) relationships
return $this->morphTo(); // e.g., Photo::imageable()
return $this->morphMany('App\Photo', 'imageable'); // e.g., Staff::photos()
Relation::morphMap([
    'Post' => App\Post::class,
    'Comment' => App\Comment::class,
]);

// Polymorphic many‑to‑many
return $this->morphToMany('App\Tag', 'taggable'); // Post::tags()
return $this->morphedByMany('App\Post', 'taggable'); // Tag::posts()

// Querying relationships
$user->posts()->where('active', 1)->get();
$posts = App\Post::has('comments')->get(); // at least one comment
$posts = Post::has('comments', '>=', 3)->get(); // at least three comments
$posts = Post::has('comments.votes')->get(); // comments with votes
$posts = Post::whereHas('comments', function($query) {
    $query->where('content', 'like', 'foo%');
})->get();

// Eager loading
$books = App\Book::with('author')->get();
$books = App\Book::with('author', 'publisher')->get();
$books = App\Book::with('author.contacts')->get();
// Lazy eager loading
$books->load('author', 'publisher');

// Saving related models
$comment = new App\Comment(['message' => 'A new comment.']);
$post->comments()->save($comment);
$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);
$post->comments()->create(['message' => 'A new comment.']);

// Updating belongs‑to relationship
$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();

// Attaching / detaching many‑to‑many
$user->roles()->attach($roleId);
$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->detach($roleId); // remove single role
$user->roles()->detach(); // remove all roles
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);
$user->roles()->sync([1, 2, 3]); // remove IDs not in array
$user->roles()->sync([1 => ['expires' => true], 2, 3]); // extra pivot data

Model Events

Model::retrieved(function ($model) {});
Model::creating(function ($model) {});
Model::created(function ($model) {});
Model::updating(function ($model) {});
Model::updated(function ($model) {});
Model::saving(function ($model) {});
Model::saved(function ($model) {});
Model::deleting(function ($model) {});
Model::deleted(function ($model) {});
Model::restoring(function ($model) {});
Model::restored(function ($model) {});
Model::observe(new FooObserver);

Eloquent Configuration

// Disable mass‑assignment protection globally
Eloquent::unguard();
// Re‑enable protection
Eloquent::reguard();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackenddatabaseORMPHPModelLaravelEloquent
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.