Laravel Eloquent (Object-Relational Mapping


Eloquent ORM (Object-Relational Mapping) is Laravel’s built-in ORM that provides a beautiful, simple Active Record implementation for working with your database. It allows you to interact with your database using a more intuitive, object-oriented approach rather than writing raw SQL queries. Eloquent makes it easier to perform common database operations and manage relationships between your models.

Key Concepts of Eloquent ORM

  1. Model Definition: In Eloquent, each database table corresponds to a model. Models are typically stored in the app/Models directory. You create a model by extending the Illuminate\Database\Eloquent\Model class.

    Example of a basic model:

    namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { // The table associated with the model. protected $table = 'posts'; // The attributes that are mass assignable. protected $fillable = ['title', 'content']; }

    Here, the Post model represents the posts table in the database, and the $fillable property specifies which attributes can be mass-assigned.

  2. Basic CRUD Operations: Eloquent makes it easy to perform CRUD (Create, Read, Update, Delete) operations.

    • Create:

      // Using the `create` method to insert a new record Post::create([ 'title' => 'New Post', 'content' => 'Content of the new post', ]);
    • Read:

      // Retrieve all records $posts = Post::all(); // Retrieve a single record by primary key $post = Post::find(1); // Retrieve a single record with a specific condition $post = Post::where('title', 'New Post')->first();
    • Update:

      // Find a record and update it $post = Post::find(1); $post->title = 'Updated Title'; $post->save();
    • Delete:

      // Find a record and delete it $post = Post::find(1); $post->delete();
  3. Mass Assignment: Eloquent allows you to mass-assign attributes to models. You need to specify which attributes are mass assignable using the $fillable property or specify which attributes are not mass assignable using the $guarded property.

    // Mass assignment using $fillable Post::create([ 'title' => 'Title', 'content' => 'Content', ]);
  4. Relationships: Eloquent makes it easy to define and work with relationships between models. Common relationships include:

    • One-to-One:

      // In the Post model public function author() { return $this->hasOne(Author::class); } // In the Author model public function post() { return $this->belongsTo(Post::class); }
    • One-to-Many:

      // In the Post model public function comments() { return $this->hasMany(Comment::class); } // In the Comment model public function post() { return $this->belongsTo(Post::class); }
    • Many-to-Many:

      // In the Post model public function tags() { return $this->belongsToMany(Tag::class); } // In the Tag model public function posts() { return $this->belongsToMany(Post::class); }

    Relationships are defined using methods on the model class and can be queried easily using Eloquent.

  5. Query Builder: Eloquent provides a fluent query builder to construct queries. It supports various query operations like where, orderBy, groupBy, etc.

    Example:

    // Retrieve posts with a specific condition and order $posts = Post::where('status', 'published') ->orderBy('created_at', 'desc') ->get();
  6. Accessors and Mutators: Accessors and mutators allow you to manipulate model attributes when they are retrieved or set.

    • Accessor:

      // In the Post model public function getTitleAttribute($value) { return ucfirst($value); }
    • Mutator:

      // In the Post model public function setTitleAttribute($value) { $this->attributes['title'] = strtolower($value); }
  7. Scopes: Scopes allow you to encapsulate common query logic within your model.

    • Local Scope:

      // In the Post model public function scopePublished($query) { return $query->where('status', 'published'); } // Using the local scope $posts = Post::published()->get();
    • Global Scope:

      // Define a global scope namespace App\Scopes; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; class PublishedScope implements Scope { public function apply(Builder $builder, Model $model) { $builder->where('status', 'published'); } } // Apply the global scope namespace App\Models; use App\Scopes\PublishedScope; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected static function booted() { static::addGlobalScope(new PublishedScope); } }
  8. Eager Loading: Eager loading is used to optimize performance by loading relationships with the initial query, reducing the number of queries executed.

    Example:

    // Eager load comments for posts $posts = Post::with('comments')->get();
  9. Soft Deletes: Soft deletes allow you to keep records in the database but mark them as deleted. This is useful for data recovery and audit purposes.

    • Using Soft Deletes:

      use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
    • Querying Soft Deleted Records:

      // Include soft deleted records $posts = Post::withTrashed()->get(); // Only soft deleted records $posts = Post::onlyTrashed()->get();

Summary

Eloquent ORM in Laravel provides a powerful, expressive, and convenient way to interact with your database. It simplifies common database operations and allows for advanced features like relationships, query scopes, and eager loading. Key aspects include:

  • Model Definition: Represents database tables and provides methods for CRUD operations.
  • Mass Assignment: Allows setting attributes in bulk.
  • Relationships: Defines and manages relationships between models.
  • Query Builder: Constructs and executes database queries fluently.
  • Accessors and Mutators: Manipulate attribute values when retrieving or setting them.
  • Scopes: Encapsulate common query logic.
  • Eager Loading: Optimizes performance by loading related data in advance.
  • Soft Deletes: Allows for data recovery by marking records as deleted rather than removing them from the database.

Eloquent ORM abstracts the complexity of SQL queries and provides a clean, object-oriented approach to managing your application's data.