Milind Daraniya

Laravel Eloquent ORM: Best Practices and Examples

Published January 5th, 2023 29 min read

Laravel's Eloquent ORM (Object-Relational Mapping) is a powerful and elegant database query builder that simplifies database interactions and allows developers to work with databases using PHP syntax. In this post, we will explore best practices for using Laravel Eloquent ORM and provide examples to illustrate its capabilities.

Setting Up Eloquent

Before using Eloquent, ensure you have a working database connection in your Laravel project. Eloquent works seamlessly with Laravel's database configuration.

Best Practice: Define Eloquent Models

Start by creating Eloquent models that represent your database tables. Models help abstract the database structure and provide an object-oriented interface to interact with the database.

Example:

// User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    // Model-specific configurations and relationships go here
}

Retrieving Data

Eloquent provides a clean and expressive syntax for querying data from the database.

Best Practice: Use Fluent Query Builder

Eloquent's query builder allows you to chain methods and build complex queries with ease.

Example: Retrieve all users whose age is greater than 25.

$users = User::where('age', '>', 25)->get();

Best Practice: Eager Loading Relationships

Eager loading reduces the number of database queries by loading related models in a single query.

Example: Retrieve all posts with their associated authors.

$posts = Post::with('author')->get();

Creating and Updating Records

Eloquent simplifies record creation and updating.

Best Practice: Mass Assignment Protection

Protect against mass assignment vulnerability by specifying which attributes can be mass-assigned using the fillable or guarded property in the model.

class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
}

Best Practice: Save and Update Methods

Use the save method for creating new records and the update method for updating existing records.

Example: Creating a new user and updating their email.

// Creating a new user
$user = new User(['name' => 'John Doe', 'email' => 'john@example.com']);
$user->save();

// Updating the email
$user = User::find(1);
$user->email = 'new_email@example.com';
$user->save();

Deleting Records

Eloquent provides simple methods to delete records.

Best Practice: Soft Deleting

Soft deleting allows you to mark records as "deleted" without actually removing them from the database. Use the softDeletes trait in the model and add a deleted_at column to the database table.

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

Example: Soft deleting a user.

$user = User::find(1);
$user->delete();

Best Practice: Force Deleting

To permanently remove a record, use the forceDelete method.

Example: Permanently deleting a user.

$user = User::find(1);
$user->forceDelete();

Query Scopes

Query scopes allow you to encapsulate common query logic in reusable methods.

Best Practice: Define Query Scopes

Define query scopes in your Eloquent model to enhance code readability and maintainability.

Example: Scope to retrieve active users.

class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }
}

Usage:

$activeUsers = User::active()->get();

Laravel Eloquent ORM offers an elegant and efficient way to interact with databases using PHP. By following best practices and leveraging Eloquent's expressive syntax, you can build scalable and maintainable database queries in your Laravel projects. Eloquent's ability to handle relationships, retrieve data, and perform CRUD operations with ease makes it a valuable tool for any Laravel developer.