How to Use Eloquent ORM in Laravel 11 Application

Using the Eloquent ORM in Laravel 11 makes database interactions seamless and efficient. Eloquent provides an ActiveRecord implementation to work with your database tables, allowing you to interact with your database using PHP syntax. Here’s a comprehensive guide on how to use Eloquent ORM in Laravel 11:

Setting Up Eloquent

Before using Eloquent, you need to create a model. Models in Laravel represent database tables. To create a model, you can use the artisan command:

php artisan make:model modelName

Replace modelName with the name of your model.

Basic CRUD Operations

Creating Records

To create a new record, simply create a new instance of your model and set its properties, then call the save() method:

$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();

Reading Records

To retrieve records, you can use various methods provided by Eloquent:

// Find a record by its primary key
$user = User::find($id);

// Find the first record matching the query
$user = User::where('name', 'John Doe')->first();

// Get all records
$users = User::all();

Updating Records

To update a record, retrieve it first and then change its attributes:

$user = User::find($id);
$user->name = 'Jane Doe';
$user->save();

Deleting Records

To delete a record, call the delete() method on the model:

$user = User::find($id);
$user->delete();

Relationships

Eloquent allows you to define relationships between your models. For example, if a User belongs to a Role, you can define this relationship in the User model:

class User extends Model
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}

Then you can access the role of a user like this:

$user = User::find($id);
$role = $user->role;

Conclusion

Eloquent ORM in Laravel 11 simplifies database operations and allows you to work with your database using expressive PHP syntax. With its powerful features like relationships and query builder, Eloquent makes working with databases in Laravel a breeze.

Leave a Reply