Skip to content

Instantly share code, notes, and snippets.

@ranjit485
Created November 18, 2025 06:15
Show Gist options
  • Select an option

  • Save ranjit485/a692ebcaf4c4c916ba6b11fd7487efc0 to your computer and use it in GitHub Desktop.

Select an option

Save ranjit485/a692ebcaf4c4c916ba6b11fd7487efc0 to your computer and use it in GitHub Desktop.
@ranjit485
Copy link
Author

Laravel Eloquent Cheat Sheet

πŸš€ 1. Basic Retrieval

User::all();
User::find(5);
User::findOrFail(5);
User::where('status', 'active')->first();

πŸ” 2. Filtering Queries

// Simple where
User::where('status', 'active')->get();

// Multiple conditions
User::where('status', 'active')->where('role', 'admin')->get();

// OR
User::where('role', 'admin')->orWhere('role', 'manager')->get();

// whereIn
User::whereIn('id', [1,2,3])->get();

// whereBetween
Order::whereBetween('amount', [100, 500])->get();

// whereNull
User::whereNull('email_verified_at')->get();

✏️ 3. Insert / Update / Delete

// Create
User::create([
    'name' => 'Ranjit',
    'email' => 'ranjit@example.com',
    'password' => bcrypt('123456')
]);

// Save
$user = new User();
$user->name = 'Ranjit';
$user->email = 'ranjit@example.com';
$user->password = bcrypt('123456');
$user->save();

// Update
User::where('id', 5)->update(['name' => 'Updated Name']);

// Delete
User::find(5)->delete();
User::destroy([1,2,3]);

πŸ“Š 4. Aggregates

User::count();
Order::max('amount');
Order::min('amount');
Order::sum('amount');
Order::avg('amount');

πŸ”— 5. Relationships

➀ One-to-One

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

➀ One-to-Many

public function comments() {
    return $this->hasMany(Comment::class);
}

➀ Belongs To

public function post() {
    return $this->belongsTo(Post::class);
}

➀ Many-to-Many

public function courses() {
    return $this->belongsToMany(Course::class);
}

⚑ 6. Eager Loading

Post::with('comments', 'category')->get();
$post->load('comments');

πŸ“„ 7. Pagination

User::paginate(10);
User::simplePaginate(15);

πŸ—‚οΈ 8. Soft Deletes

Model Setup

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {
    use SoftDeletes;
}

Soft Delete Queries

User::withTrashed()->get();
User::onlyTrashed()->get();
User::withTrashed()->find(5)->restore();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment