DEV Community

Cover image for Mastering Eloquent ORM: A Beginner's Guide to Laravel's Magic ๐Ÿš€
Ionut Cornea
Ionut Cornea

Posted on

Mastering Eloquent ORM: A Beginner's Guide to Laravel's Magic ๐Ÿš€

[Laravel beginner series | Part 3]

๐Ÿ‘‹ What's up folks! This is the third article from the Laravel beginner series! Let's get straight to it!

๐Ÿ‘‰Introduction

If you've ever worked with databases in PHP, you probably know the struggle of writing raw SQL queries. They're powerful but can quickly become complex and hard to manage. Thankfully, Laravel provides Eloquent ORM a simple yet powerful way to interact with your database using object-oriented syntax.

In this article, we'll break down Eloquent ORM into easy-to-understand concepts, covering everything from basic queries to relationships.
By the end, you'll be able to use Eloquent like a pro! ๐Ÿ’ช

๐Ÿ‘‰What is Eloquent ORM? ๐Ÿง

Image description

Eloquent is Laravel's Object-Relational Mapper (ORM) that allows you to interact with your database using PHP syntax instead of writing raw SQL queries. It simplifies database operations by treating tables as models, making CRUD operations a breeze.

Think of it like this:
Instead of writing SELECT * FROM users WHERE id = 1, you can simply do:

User::find(1);
Enter fullscreen mode Exit fullscreen mode

Instead of inserting a new user with INSERT INTO users ..., you can do:

User::create(['name' => 'John Doe', 'email' => 'john@example.com']);
Enter fullscreen mode Exit fullscreen mode

Now, let's get further into the essentials of Eloquent ORM. ๐ŸŽฏ

๐Ÿ‘‰Setting Up Eloquent ๐Ÿ“ฆ

Before using Eloquent, make sure your model is correctly set up. Laravel automatically places models inside the app/Models directory.
If you're creating a new model, run:

php artisan make:model User
Enter fullscreen mode Exit fullscreen mode

This generates a User.php file inside app/Models. The model represents the users table in your database.

Database Configuration

Make sure your .env file has the correct database settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰Basic CRUD Operations ๐Ÿ› ๏ธ

Creating Records

To insert data, use the create() method:

User::create([
    'name' => 'Jane Doe',
    'email' => 'jane@example.com',
    'password' => bcrypt('password')
]);
Enter fullscreen mode Exit fullscreen mode

Note: Make sure the fillable property is defined in your model:

protected $fillable = ['name', 'email', 'password'];
Enter fullscreen mode Exit fullscreen mode

Reading Records

Fetching all users:

$users = User::all();
Enter fullscreen mode Exit fullscreen mode

Finding a user by ID:

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

Retrieving a user with conditions:

$user = User::where('email', 'jane@example.com')->first();
Enter fullscreen mode Exit fullscreen mode

Updating Records

$user = User::find(1);
$user->name = 'Jane Doe Updated';
$user->save();
Enter fullscreen mode Exit fullscreen mode

Or using update():

User::where('id', 1)->update(['name' => 'Jane Updated']);
Enter fullscreen mode Exit fullscreen mode

Deleting Records

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

Or:

User::destroy(1);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰Relationships in Eloquent ๐Ÿค

Eloquent makes defining relationships between models super easy. Letโ€™s explore the most common ones.

One-to-One Relationship

A user has one profile:

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

Fetching a user's profile:

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

One-to-Many Relationship

A user has many posts:

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

Fetching user's posts:

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

Many-to-Many Relationship

Users can have multiple roles, and roles can belong to multiple users:

class User extends Model {
    public function roles() {
        return $this->belongsToMany(Role::class);
    }
}
Enter fullscreen mode Exit fullscreen mode

Fetching user's roles:

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

๐Ÿ‘‰Query Scopes for Cleaner Code โœจ

Query scopes allow you to create reusable query logic in your model.

class User extends Model {
    public function scopeActive($query) {
        return $query->where('status', 'active');
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you can call:

$activeUsers = User::active()->get();
Enter fullscreen mode Exit fullscreen mode

Conclusion ๐ŸŽ‰

Eloquent ORM is a game-changer when working with databases in Laravel. It simplifies CRUD operations, relationships, and query building, making your code more readable and maintainable. ๐Ÿš€

If you're new to Laravel, start using Eloquent in your projects and experience the magic of database management without the headache of raw SQL. Happy coding! ๐ŸŽจ๐Ÿ’ป

๐Ÿ”ฅ Want to Learn More?
Here you have the awesome and really clean documentation of Laravel.

Also, here you have the Laravel community from Reddit.

If you found this guide helpful, leave a โค๏ธ and share it with fellow developers! ๐Ÿš€

See you next week!

Top comments (0)