Introduction to Laravel Eloquent

Introduction to Laravel Eloquent

Laravel has consistently delivered robust tools for developers, enhancing productivity and simplifying common web development tasks. One of the standout components of Laravel is Eloquent, its Object-Relational Mapping (ORM) system, designed to simplify database interactions using an active record implementation.

Boost your Laravel apps with our specialized Laravel Hosting. Experience faster speeds for your Laravel applications and websites thanks to NVMe storage, server protection, dedicated resources, and optimization tools.

check mark99.99% Uptime check markFree SSL check markDedicated IP Address check markDeveloper Tools

Laravel Hosting

Prerequisites

Before diving into Eloquent, you must have Laravel installed. If you haven’t already completed this step, please see our How to Install Laravel article. A database must also be configured in the .env file at the root of your Laravel installation. See How To Configure the Laravel .env for a Database to help you with that step if you haven’t done so already.

Understanding Eloquent Models

Eloquent models are central to Eloquent ORM, which stands for Object-Relational Mapping. An ORM is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. Essentially, it creates a virtual object database that can be used from within a programming language to manipulate data. This means developers can work with data as if they were working with objects in their programming language rather than dealing with SQL queries directly.

With Eloquent, each model you create in Laravel represents a specific table in your database and each instance of a model corresponds to a row in that table. This mapping of tables to models and rows to instances simplifies the CRUD (Create, Read, Update, Delete) operations in the database.

Here’s how you can create an Eloquent model:

php artisan make:model Post

This command creates a Post model for a posts database table. By default, Laravel assumes the table name is the plural form of the model name unless explicitly specified otherwise. You can define relationships, specify the database connection, and customize table names directly within these model classes, harnessing the full power of object-oriented programming to manage your database.

This abstraction allows developers to focus more on the application’s functionality and less on the details of SQL syntax, leading to more robust and maintainable code.

Retrieving Data

Eloquent simplifies data retrieval with several methods that cover common use cases:

  • find($id) retrieves a model by its primary key.
  • all() fetches all records from the model’s database table.
  • where('column', 'value') allows condition-based queries.
  • first() returns the first record found in the query.

Here’s an example of using Eloquent to retrieve posts with a specific condition:

$posts = Post::where('status', 'published')->get();

Inserting and Updating Data

To create a new record, you instantiate a new model instance, set attributes, and call the save() method:

$post = new Post;
$post->title = 'New Post Title';
$post->content = 'Content of the post';
$post->save();

Updating data follows a similar pattern but starts with fetching a model instance:

$post = Post::find(1);
$post->title = 'Updated Title';
$post->save();

Deleting Data

Deleting data is straightforward with Eloquent. To delete a model:

$post = Post::find(1);
$post->delete();

For soft deletes, which allow records to be restored, enable them in your model by using the SoftDeletes trait:

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}

Relationships in Eloquent

Eloquent supports several types of relationships:

  • One-to-One: Each model holds a reference to one related model.
  • One-to-Many: A model can be associated with multiple models.
  • Many-to-Many: Models are connected through a pivot table.

Defining a relationship is done within a model:

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

Advanced Eloquent Features

Eloquent provides features to refine your database interactions further:

  • Eager Loading: Prevents the N+1 query problem with with() method.
  • Mutators and Accessors: Customize how you set and get attributes on your models.
  • Scopes: Define common queries in your models to reuse throughout your application.

Best Practices with Laravel 11 Eloquent

  • Keep Eloquent queries efficient: Avoid excessive database calls by utilizing eager loading.
  • Use Scopes: To maintain cleaner controllers and reuse query logic.
  • Select Eloquent or Query Builder: Use Eloquent for most database interactions, but switch to the Query Builder for complex queries for performance optimizations.

Conclusion

Eloquent ORM in Laravel 11 offers an efficient and elegant way to interact with your database. With its active record implementation, Eloquent allows you to write database queries with PHP syntax rather than SQL. This not only speeds up the development process but also ensures clarity and maintainability of your code.

Derrell Willis
Derrell Willis Manager, Developer Relations

More Articles by Derrell

Was this article helpful? Join the conversation!