How to Use Eloquent ORM (Object Relational Mapping) in Laravel

If you are a Laravel developer, then you must be familiar with Eloquent ORM. It is an easy-to-use and powerful ORM (Object Relational Mapping) system that allows developers to interact with databases using PHP code instead of writing SQL queries. In this article, we will explore Eloquent ORM in Laravel and provide examples to help you understand how it works.

Introduction to Eloquent ORM

Eloquent ORM is a powerful and intuitive database ORM that comes with the Laravel PHP framework. It provides a simple and expressive way to interact with databases using PHP. With Eloquent ORM, you can easily perform CRUD (Create, Read, Update, Delete) operations on database tables.

The key feature of Eloquent ORM is the ability to map database tables to PHP classes. Each database table can be represented as a PHP class and each table row as an instance of that class. This allows developers to interact with databases using an object-oriented programming (OOP) approach, making code more readable and maintainable.

Setting up Eloquent ORM

Before we dive into the code, let’s first set up Eloquent ORM in Laravel. Laravel already comes with Eloquent ORM pre-installed, so we don’t need to install any additional packages. We only need to create a model class for each database table we want to interact with.

To create a model class, simply use the make:model Artisan command in your terminal. For example, to create a User model for the users table, run the following command:

php artisan make:model User

This will create a User model class in the app directory. You can now use this model class to interact with the users table.

Defining Model Relationships

Eloquent ORM also provides an easy way to define relationships between database tables. For example, let’s say we have a posts table and a users table. Each post belongs to a user and each user can have multiple posts.

To define this relationship in Eloquent ORM, we can use the belongsTo and hasMany methods in our model classes. In the Post model, we would define the relationship as follows:

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

This defines a belongsTo relationship between the Post model and the User model. We can now easily retrieve the user associated with a post using the user method:

$post = Post::find(1);
$user = $post->user;

In the User model, we would define the relationship as follows:

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

This defines a hasMany relationship between the User model and the Post model. We can now easily retrieve all posts associated with a user using the posts method:

$user = User::find(1);
$posts = $user->posts;

Querying with Eloquent ORM

Eloquent ORM provides a simple and intuitive way to query databases using PHP. For example, let’s say we want to retrieve all users from the users table. We can do this using the all method in our User model:

$users = User::all();

This will retrieve all users from the users table and return them as a collection of User objects.

We can also filter and sort data using Eloquent ORM. For example, let’s say We want to retrieve all users who are active and whose name starts with “J”. We can do this using the where method:

$users = User::where('is_active', true)
             ->where('name', 'like', 'J%')
             ->get();

This will retrieve all active users whose name starts with “J” and return them as a collection of User objects.

Eloquent ORM also supports pagination, so we can retrieve a limited number of results at a time. For example, let’s say we want to retrieve 10 users per page. We can do this using the paginate method:

$users = User::paginate(10);

This will retrieve the first 10 users and return them as a collection of User objects. We can then use the links method to display pagination links:

{{ $users->links() }}

Creating and Updating Data

Eloquent ORM also provides an easy way to create and update data in databases. For example, let’s say we want to create a new user:

$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();

This will create a new user in the users table.

We can also update data using Eloquent ORM. For example, let’s say we want to update the name of a user:

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

This will update the name of the user with ID 1 in the users table.

Conclusion

In this article, we have explored the power of Eloquent ORM in Laravel. We have seen how to set up Eloquent ORM, define model relationships, query data, and create and update data. Eloquent ORM provides an easy-to-use and powerful way to interact with databases using PHP code, making development faster and more efficient.

FAQs

What is Eloquent ORM?

Eloquent ORM is a database ORM that comes with the Laravel PHP framework. It allows developers to interact with databases using PHP code instead of writing SQL queries.

How do I set up Eloquent ORM in Laravel?

Eloquent ORM is pre-installed in Laravel, so you don’t need to install any additional packages. Simply create a model class for each database table you want to interact with.

What are model relationships in Eloquent ORM?

Model relationships define the relationships between database tables. For example, a belongsTo relationship defines that a row in one table belongs to a row in another table.

How do I query data using Eloquent ORM?

You can use the all method to retrieve all rows from a table, or the where method to filter rows based on certain criteria. You can also use pagination to retrieve a limited number of results at a time.

How do I create and update data using Eloquent ORM?

You can create a new row by instantiating a new model object and setting its properties, then calling the save method. You can update an existing row by retrieving it using the find method, updating its properties, then calling the save method.

Leave a comment

0.0/5