DEV Community

Janet Awino
Janet Awino

Posted on

How to Use Eloquent ORM for Database Management in Laravel

Laravel’s Eloquent ORM (Object-Relational Mapping) is one of the most popular features of the framework. It provides a clean, intuitive way to interact with your database, allowing you to work with tables as simple PHP objects. With Eloquent, you can handle complex database operations without writing long and repetitive SQL queries.
This article will walk you through the essentials of using Eloquent ORM for database management, covering everything from creating models to handling relationships and best practices. By the end, you’ll be equipped to use Eloquent effectively in your Laravel projects.

1. Setting Up Eloquent

Before diving into Eloquent, make sure you have a Laravel project set up. If you don’t already have one, you can create it by running the following command:

composer create-project laravel/laravel example-app
Enter fullscreen mode Exit fullscreen mode

Configuring Your Database
Next, configure your database connection in the .env file located in the root directory of your Laravel project:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=your_database_name  
DB_USERNAME=your_username  
DB_PASSWORD=your_password  
Enter fullscreen mode Exit fullscreen mode

Run the following command to create the default database tables, such as the users table:

php artisan migrate  
Enter fullscreen mode Exit fullscreen mode

Your project is now ready to use Eloquent ORM.

2. Creating a Model

What is a Model?
A model in Eloquent represents a single database table. Each model corresponds to a table, and each instance of the model represents a row in that table. Models handle most of the data manipulation tasks in Laravel.
Creating a Model
To create a new model, use the Artisan command:

php artisan make:model Post -m  
Enter fullscreen mode Exit fullscreen mode

The -m flag creates a migration file for your model. This migration file defines the structure of the corresponding database table. Open the migration file in the database/migrations directory and define the columns:

Schema::create('posts', function (Blueprint $table) {  
    $table->id();  
    $table->string('title');  
    $table->text('body');  
    $table->timestamps();  
});  
Enter fullscreen mode Exit fullscreen mode

Run the migration to create the posts table:

php artisan migrate  
Enter fullscreen mode Exit fullscreen mode

3. Retrieving Data with Eloquent

Retrieving data is one of the most common tasks in database management. With Eloquent, this is incredibly simple.
Retrieve All Records
To fetch all records from a table, use the all() method:

$posts = Post::all();  
foreach ($posts as $post) {  
    echo $post->title;  
}  
Enter fullscreen mode Exit fullscreen mode

Retrieve a Single Record
You can fetch a single record using the find() method with a primary key:

$post = Post::find(1); 
echo $post->title;   
Enter fullscreen mode Exit fullscreen mode

Alternatively, use the first() method to retrieve the first matching record:

$post = Post::where('title', 'First Post')->first();  
Enter fullscreen mode Exit fullscreen mode

Use Filters and Conditions
Eloquent allows you to filter results with the where() method:

$posts = Post::where('title', 'like', '%Laravel%')->get();  
Enter fullscreen mode Exit fullscreen mode

4. Inserting Data with Eloquent

Eloquent simplifies the process of adding new records to your database.
Mass Assignment with Create Method
To use mass assignment, define the fillable property in your model to specify the fields that can be mass-assigned:

class Post extends Model  
{  
    protected $fillable = ['title', 'body'];  
}  
Enter fullscreen mode Exit fullscreen mode

Now you can create a new record like this:

Post::create([  
    'title' => 'New Post',  
    'body' => 'This is the body of the new post.',  
]);  
Enter fullscreen mode Exit fullscreen mode

Using the Save Method
Another way to add data is by creating a model instance and saving it:

$post = new Post();  
$post->title = 'Another Post';  
$post->body = 'This is another post body.';  
$post->save();  
Enter fullscreen mode Exit fullscreen mode

5. Updating Data with Eloquent

Find and Update
To update a record, fetch it first, then modify and save it:

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

Direct Update Method
If you don’t need to fetch the record first, use the update() method:

Post::where('id', 1)->update(['title' => 'Another Updated Title']);  
Enter fullscreen mode Exit fullscreen mode

6. Deleting Data with Eloquent

Deleting a Record
To delete a specific record, find it first, then call the delete() method:

$post = Post::find(1);  
$post->delete();  
Enter fullscreen mode Exit fullscreen mode

Bulk Deletion
To delete multiple records based on a condition, use the where() method followed by delete():

Post::where('title', 'Old Post')->delete();
Enter fullscreen mode Exit fullscreen mode

7. Eloquent Relationships

Eloquent supports relationships, making it easy to manage associations between tables.
One-to-One
A one-to-one relationship links one record in a table to one record in another.

// User model  
public function profile()  
{  
    return $this->hasOne(Profile::class);  
}  
Enter fullscreen mode Exit fullscreen mode

Fetch the profile of a user:

$user = User::find(1);  
$profile = $user->profile;  
Enter fullscreen mode Exit fullscreen mode

One-to-Many
A one-to-many relationship links one record in a table to multiple records in another.

// User model  
public function posts()  
{  
    return $this->hasMany(Post::class);  
} 
Enter fullscreen mode Exit fullscreen mode

Fetch all posts for a user:

$user = User::find(1);  
$posts = $user->posts; 
Enter fullscreen mode Exit fullscreen mode

Many-to-Many
A many-to-many relationship links records in one table to many records in another.

// Post model  
public function tags()  
{  
    return $this->belongsToMany(Tag::class);  
}  
Enter fullscreen mode Exit fullscreen mode

Attach tags to a post:

$post = Post::find(1);  
$post->tags()->attach([1, 2]); 
Enter fullscreen mode Exit fullscreen mode

8. Query Scopes

Query scopes allow you to reuse query logic.
Defining a Query Scope
Add a scope method to your model:

public function scopePopular($query)  
{  
    return $query->where('views', '>', 100);  
}  
Using a Scope
$popularPosts = Post::popular()->get();  
Enter fullscreen mode Exit fullscreen mode

9. Eloquent Events

Eloquent events let you perform actions during a model’s lifecycle.
Using Events
For example, automatically generate a slug when creating a post:
protected static function booted()

{  
    static::creating(function ($post) {  
        $post->slug = Str::slug($post->title);  
    });  
} 
Enter fullscreen mode Exit fullscreen mode

10. Best Practices for Eloquent ORM

  • Use Fillable Fields: Always define the fillable property to avoid mass assignment vulnerabilities.
  • Eager Load Relationships: Use with()to load related models in fewer queries.
  • Optimize Queries: Use scopes, caching, and indexingfor better performance.
  • Validate Inputs: Always validatedata before saving it to the database.

Conclusion

Eloquent ORM is a powerful and flexible tool for managing databases in Laravel. It simplifies common tasks like querying, inserting, updating, and deleting records while supporting advanced features like relationships and events. By mastering Eloquent, you can make your Laravel development faster and more efficient.
Try these examples in your next project to see how Eloquent can transform the way you handle database management.

Top comments (0)