[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? 🧐
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);
Instead of inserting a new user with INSERT INTO users ...
, you can do:
User::create(['name' => 'John Doe', 'email' => 'john@example.com']);
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
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=
👉Basic CRUD Operations 🛠️
Creating Records
To insert data, use the create()
method:
User::create([
'name' => 'Jane Doe',
'email' => 'jane@example.com',
'password' => bcrypt('password')
]);
Note: Make sure the fillable property is defined in your model:
protected $fillable = ['name', 'email', 'password'];
Reading Records
Fetching all users:
$users = User::all();
Finding a user by ID:
$user = User::find(1);
Retrieving a user with conditions:
$user = User::where('email', 'jane@example.com')->first();
Updating Records
$user = User::find(1);
$user->name = 'Jane Doe Updated';
$user->save();
Or using update():
User::where('id', 1)->update(['name' => 'Jane Updated']);
Deleting Records
$user = User::find(1);
$user->delete();
Or:
User::destroy(1);
👉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);
}
}
Fetching a user's profile:
$user = User::find(1);
$profile = $user->profile;
One-to-Many Relationship
A user has many posts:
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}
Fetching user's posts:
$posts = User::find(1)->posts;
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);
}
}
Fetching user's roles:
$roles = User::find(1)->roles;
👉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');
}
}
Now you can call:
$activeUsers = User::active()->get();
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 (2)
thank you 💗
Be blessed