Eloquent ORM Tutorial
What is Eloquent ORM?
Eloquent ORM (Object-Relational Mapping) is an advanced PHP implementation for interacting with databases in the Laravel framework. It allows developers to interact with database records as if they were simple PHP objects, making data manipulation more intuitive and easier to manage.
Setting Up Eloquent
To use Eloquent ORM, you need to ensure that you have a Laravel project set up. You can create a new Laravel project using Composer:
Once your project is set up, configure your database settings in the .env
file:
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
Creating a Model
In Eloquent, each database table has a corresponding "Model" that allows you to interact with that table. You can create a new model using the Artisan command:
This command creates a new model named Product
in the app/Models
directory. The model will be used to interact with the products
table in your database.
Basic CRUD Operations
Create
To create a new record in the database using Eloquent, you can use the following syntax:
$product = new Product;
$product->name = 'New Product';
$product->price = 99.99;
$product->save();
Read
To retrieve records from the database, you can use the all()
method:
Update
To update an existing record, you first need to retrieve it and then modify its properties:
$product->price = 79.99;
$product->save();
Delete
To delete a record, you can use the delete()
method:
$product->delete();
Querying with Eloquent
Eloquent provides a powerful, fluent interface for querying your database. Here are some examples:
Where Clauses
Ordering Results
Pagination
Relationships
Eloquent makes managing relationships between different models easy. Common relationships include:
One-to-Many
For example, if you have a Category
model that can have many Product
models:
public function products() {
return $this->hasMany(Product::class);
}
}
Many-to-Many
For a many-to-many relationship, you can define it like this:
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
Conclusion
Eloquent ORM is a powerful tool in Laravel that simplifies database interactions. This tutorial covered the basics, including model creation, CRUD operations, querying, and relationships. By leveraging Eloquent, developers can write clean, maintainable code while efficiently interacting with their database.