DEV Community

Cover image for Eloquent ORM: First Steps.
Andres Castro
Andres Castro

Posted on • Updated on

Eloquent ORM: First Steps.

When I started working I had no knowledge of backend development. Even though I was hired as a Front End Dev, I was soon required to work on backend tasks using Laravel. The first days were quite daunting. It was only after grasping how to actually interact with the database that I started feeling like I was not lost. No2, I want to share my understanding on the most basic usage of Laravel's Eloquent Model, hoping to help you have a better starting point than I had.

What is Eloquent?

Eloquent is Laravel's Object Relational Mapping (ORM). We can understand this as a bridge between object-oriented programming and relational databases. The whole idea behind an ORM is to use your knowledge in OOP to manipulate your database, which should be easier and more enjoyable than doing so directly without the ORM.

Now, let's see the basic functionality of Eloquent. For this, I'll use some examples of a Shipping App I've been working on.

Eloquent Basics

Models

The basic element in Eloquent is a "model". Models are like blueprints for database tables. Let's see an example with a "Parcel" table containing dimensions and other relevant parcel info:

Model Example

As seen in the picture, the model shows a list of the columns we are going to have in our DataBase Table. Also, by making them "fillable" we are telling Laravel that those fields can be edited by us.

Below the listing of columns, we can find some public functions. These functions allow us to relate this model (table) to other models. In this example, we are determining that any Parcel we create belongs to a specific customer and a specific shipment that was bought. This will allow us to later retrieve parcel information as if it was part of the shipments table, even when the information is not actually on the shipment table. This is the magic of a relational database.

Migrations

As said before, the model determines the fields and relations of a certain table. On the other hand, a migration is an actual representation of said table. Let's see the corresponding migration for our parcel model:

Migration Example

Here, we can define certain constraints for our columns. First and most importantly, we define the type of data that can be stored in each field. Besides that, we can also define some properties like a default value if no data is added and if a field can be null or has to be filled.

Within the migration we must also pay special attention to a new concept: table ids.

As seen in the first line, we find the id of the current table. This is an integer that would increment +1 automatically, giving every row a unique id. Furthermore, we can see (on lines 28 and 29) 2 foreign ids. These ids belong to the 2 tables we previously related in the model: Customer and Shipments. In this way, whenever we save a parcel we can pass in the ids of the Customer and the Shipment it belongs to. This is what will finally be used by our Database to connect (relate) the corresponding series of data between tables.

Controllers

Finally, the last piece of the puzzle are controllers. These are basically classes where we define all the logic to be executed in our program. It is most common to create all 3 components: Model, Migration, and Controller. Depending on the requirements of your app, you might not always need a controller. In the current example, there is no "ParcelController" but rather a "ShipmentController", because everything related to a parcel will be dependent on a shipment.

So, what can we do with a controller? In a Laravel app, we can see controllers as the core of our backend, which means there's much we can do. Let's then focus again on our database. There are two main actions we want to achieve regarding our data: storing and retrieving.

Storaging data

Storing data is pretty straightforward. My preferred way of doing this is to create an associative array with all the corresponding data to be saved:

Store Data Example

As we can see from the picture, this is just a regular PHP function. Also, note it doesn't matter where the data is coming from (variables, Session, or even from the DataBase).

Be aware, that named keys must match what we defined on our model and migration. However, the order doesn't matter, just the names. Also, be careful about not passing data. If you miss a field that has no default value or is not nullable this will cause your app to crash.

Once you create your array, it is as easy as using the Eloquent Method ::Create().

Retrieving Data:

Retrieving data can be as easy as storing it, but it is also quite tricky depending on how complex your relations are. To achieve this we always need to do some sort of query, in order to let the DB know what is it that we want. Let's imagine a certain scenario where we want to return information about a certain Shipment and all data associated with it.

Query Example

Let's walk through this example. First, we can see there is a tracking code parameter being received. In the body of the function, we define the $shipment variable and assign it to our query. The first part is using Eloquent to fetch our Shipment model (Shipment::) and the rest of the expression is the actual query. Here we see three different methods.
where() which allows us to compare. In this case, it means "retrieve only shipments where its tracking code column equals our tracking code variable". Then we have with() which allows us to access the relations that live in the model like the carrier and customer. We could even load Parcel data if we wished. Lastly the first() method allows us to only retrieve one row of the Database and not the whole model (which we actually retrieved with the other two methods).

The result of this query is an associative array with all the data we requested.

Wrapping UP

Eloquent ORM allows us to manipulate database data within the realms of OOP. In Laravel, we need a model (defines fields and relations), a migration (actual table to be created), and a controller (where our logic is placed for actually manipulating the data).

What next?

Hope you now have a good understanding of the fundamentals of manipulating a relational database through Eloquent. From here, I would highly recommend studying queries and the many possibilities for building them. Also, there are many details about migrations outside the scope of this lecture so it's a great idea for you to read about migration manipulation. Lastly, consider there is no need to code all these components from scratch. I suggest you look at creating controllers with migration and model through Laravel's Artisan CLI.

Top comments (0)