Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

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:

composer create-project --prefer-dist laravel/laravel projectName

Once your project is set up, configure your database settings in the .env file:

DB_CONNECTION=mysql
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:

php artisan make:model Product

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:

use App\Models\Product;
$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:

$products = Product::all();

Update

To update an existing record, you first need to retrieve it and then modify its properties:

$product = Product::find(1);
$product->price = 79.99;
$product->save();

Delete

To delete a record, you can use the delete() method:

$product = Product::find(1);
$product->delete();

Querying with Eloquent

Eloquent provides a powerful, fluent interface for querying your database. Here are some examples:

Where Clauses

$products = Product::where('price', '>', 50)->get();

Ordering Results

$products = Product::orderBy('price', 'desc')->get();

Pagination

$products = Product::paginate(10);

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:

class Category extends Model {
public function products() {
return $this->hasMany(Product::class);
}
}

Many-to-Many

For a many-to-many relationship, you can define it like this:

class Product extends Model {
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.