Krishnan's Personal Website


Home | About | Blog | Interesting Reads | Tutorials | Skills | Personal Projects | Books | Fun | Connect with me


Working with Eloquent ORM in Laravel


Published On: May 14 2023
Written By: Krishnan Sethuraman
Category: PHP


Laravel is a popular PHP framework that makes it easy to build web applications quickly and efficiently. One of the key features of Laravel is its powerful object-relational mapping (ORM) tool, Eloquent. Eloquent is a simple yet powerful way to work with databases in Laravel, allowing developers to easily define database tables as classes and work with them using object-oriented syntax. In this blog post, we will explore the basics of working with Eloquent ORM in Laravel.

Getting Started with Eloquent

Eloquent provides a simple and intuitive way to work with databases in Laravel. To get started with Eloquent, we need to define our database tables as classes, and then use Eloquent to interact with them.

Let's take a look at an example. Suppose we have a database table called users that has columns for id, name, and email. To define this table as a class in Laravel, we create a new PHP file called User.php in the app directory and define a new class called User. We then use the extends keyword to inherit from Laravel's built-in Model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
}

In this code, we first declare the namespace of our class as App. We then import the Model class from Laravel's Eloquent package, which we extend with our User class. Finally, we define the name of our database table by setting the $table property to 'users'.

Retrieving Records with Eloquent

Now that we have defined our database table as a class in Laravel, we can use Eloquent to retrieve records from the table. Let's take a look at an example. Suppose we want to retrieve all the records from the users table. We can do this using the following code:

$users = User::all();

 

In this code, we use the all() method of the User class to retrieve all the records from the users table. The resulting $users variable will contain an array of User objects, one for each record in the table.

We can also use Eloquent to retrieve a single record from the table. Let's take a look at an example. Suppose we want to retrieve the record with an id of 1 from the users table. We can do this using the following code:

$user = User::find(1);

 

In this code, we use the find() method of the User class to retrieve the record with an id of 1 from the users table. The resulting $user variable will contain a single User object.

Querying the Database with Eloquent

In addition to retrieving records from the database, we can also use Eloquent to query the database and retrieve only the records that match certain criteria. Let's take a look at an example. Suppose we want to retrieve all the records from the users table where the name column is equal to 'John'. We can do this using the following code:

$users = User::where('name', 'John')->get();

 

In this code, we use the where() method of the User class to specify the condition that we want to match. We then use the get() method to retrieve all the records that match the condition. The resulting $users variable will contain an array of User objects, one for each record that matches the condition.

We can also use Eloquent to order the results of a query. Let's take a look at an example

$users = User::orderBy('name', 'asc')->get();


In this code, we use the orderBy() method of the User class to specify the column (name) and the order (asc for ascending) in which we want the results to be sorted. The get() method retrieves all the records from the users table, sorted according to the specified order. The resulting $users variable will contain an array of User objects, with the records ordered by name in ascending order.

Eloquent provides a wide range of query methods, allowing you to build complex queries with ease. You can use methods like where, orWhere, whereIn, whereNotNull, and many more to filter and retrieve specific records based on various conditions.

Creating and Updating Records with Eloquent
Besides retrieving records, Eloquent also simplifies the process of creating and updating records in the database. Let's look at some examples.

To create a new record in the users table, we can use the following code:

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

In this code, we create a new instance of the User class and assign values to its properties (name and email). The save() method is then called to persist the new record in the database.

To update an existing record, we can retrieve it using Eloquent, modify its properties, and save it again:

$user = User::find(1);
$user->email = 'new-email@example.com';
$user->save();


In this code, we retrieve the record with an id of 1 from the users table using the find() method. We then update the email property and call the save() method to save the changes to the database.

Eloquent also provides convenient methods like update and updateOrCreate for updating records in bulk or creating new ones if they don't exist.

Relationships with Eloquent

One of the most powerful features of Eloquent is its ability to define relationships between database tables. With relationships, you can easily retrieve related records and perform operations across multiple tables.

Let's consider an example where we have a users table and a posts table, and each user can have multiple posts. We can define a one-to-many relationship between these tables using Eloquent. In the User class, we define the relationship with the posts table as follows:

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


In the Post class, we define the inverse relationship to the users table:

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

With these relationship definitions, we can easily retrieve a user's posts or the user associated with a post. For example:

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

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

Eloquent provides various types of relationships, such as one-to-one, one-to-many, many-to-many, and polymorphic relationships, allowing you to model complex database relationships effortlessly.

Conclusion

Working with Eloquent ORM in Laravel greatly simplifies the task of interacting with databases in your web applications. It provides an elegant and intuitive syntax for retrieving, querying, creating, and updating records, as well as defining relationships between tables. With Eloquent, you can focus on writing expressive and maintain