This tutorial is out of date and no longer maintained.
The Eloquent ORM that comes with Laravel makes it incredibly easy to interact with a database. Today we’ll look at how we can use Eloquent to interact with our database and do:
The Eloquent ORM provides an ActiveRecord implementation to work with your database. This means that each model you create in your MVC structure corresponds to a table in your database.
A Bear
model will correspond to a bears
table in your database. Since we have conventions when creating our models and database tables, we can easily call data from our database.
For example, to get all bears
from a Bear
model, all you would do is Bear::all()
. Using this function would query the database and generate the proper SQL command. Here are some quick examples:
Description | Function |
---|---|
Find all bears | Bear::all() |
Find a record | Bear::find(id) |
Delete a record | Bear::delete(id) |
Super simple! There are many more applications of this and we’ll get into them further into this article.
Let’s create a sample application about bears
. Let’s say there are many bears. There are different types of bears with different weights and danger levels.
We will also say there are fish
. Each fish belongs to a single bear since bears don’t like sharing. This will be our one-to-one relationship.
Bears also love to climb trees
. Each bear will have many trees they like to climb. This will be our one-to-many relationship.
There will also be picnics
. Many bears can go to many picnics since they like to ransack as many delicious picnics as they can. This will be our many-to-many relationship.
To get started using Eloquent, we’ll need to set up our database and application. Let’s run through that real quick. We’ll need to:
composer install --prefer-dist
app/config/database.php
Those first two parts are easy enough so get those done. Then we’ll work on migrating and seeding our database.
With our migrations, we will be adding three tables to our database: bears
, fish
, and picnics
. For more information on using migrations, read the Laravel docs.
Let’s create our migration. Through the command line, type:
Let’s go in and add our fields.
By default, these migrations will include an auto-incrementing id
. It will also include timestamps for the fields created_at
and updated_at
. updated_at will be automatically updated whenever the record is updated.
Plural vs Singular Database Table Names With our bears, we can create the standard plural table name (ie bears, picnics). With fish, it’s different. Do we use fish or fishes? The good news is we can use whichever we want and then override the defaults when defining our Eloquent model
.
Since we will be creating a one-to-many relationship, we will need two tables. One for the picnics and another to link a bear to a picnic.
Now we will need a table to link our bears to a picnic. We’ll create a pivot table here. This is how we can define our many-to-many relationship.
Now we have a way to link our multiple bears to multiple picnics. This is how we create our many-to-many relationship.
With our migration files made, migrate your database using artisan:
Now that we have migrated our database, we will need to seed our database. The process of seeding however is inserting records into our database and this will require Eloquent! We will need to create our models before we can seed the database.
Let’s make our Eloquent models. This is also where we will define our relationships.
Let’s look at our Bear
model first.
Mass Assignment We have to set our mass assignable attributes so that we make sure that only the attributes we want are allowed to be changed.
Defining Relationships When defining relationships, the name of the function can be whatever you want it to be named. It makes sense here since we will be finding the fish
that belongs to the bear. On the line return $this->hasOne('Fish')
however, you will need to match the name of the Eloquent model that corresponds to that item.
There are different ways we can define relationships. There are hasOne
, hasMany
, belongsTo
, belongsToMany
, and more. Read the Eloquent Relationship docs to see all the things you can do.
Eloquent Model and Database Table Naming Conventions By default, when you define an Eloquent model, you name it for the singular term. In this case Bear
. Eloquent will then look to the database for the lowercase and plural version of that word. In this case, this model will be linked to our bears
table we created in our migration.
Here is our Fish
model.
Like we talked about earlier, since we named our table fish
, then it doesn’t follow convention. We will explicitly call out the database name using protected $table
.
Similar to how we defined our relationship in the Bear
model, we will define the inverse of that relationship. A Fish
belongs to a Bear
.
You know the drill now. Let’s make the Picnic
model.
Just like our other models, we have defined mass assignable attributes and relationships. When defining many-to-many relationships, you use belongsToMany()
and not hasMany. hasMany
is used for one-to-many relationships.
Now that we have our migrations and models done, we can seed our database. We will use Eloquent for inserting into our database for our seeds.
For more information on Eloquent concepts like creating Eloquent models, performing CRUD, or defining relationships, definitely read the Laravel Eloquent docs.
For those of you who don’t know, seeding allows us to fill our database with dummy information to play with. This is great when developing our applications and need data to populate our application.
We will create database seeders inside of the app/database/seeds/DatabaseSeeder.php
.
Usually, you would want to create separate seed files, but we’re going to dump everything into this file to make this simple. (We want to get to querying things with Eloquent already!)
In our seeder file, we are creating bears, fish, picnics, and linking many bears to one picnic.
Grabbing the ID of a Newly Created Record We need to grab the id of the inserted bears and picnic so we will save the record into a variable on creation. After doing this, we are able to pull the id using $bearLawly->id
.
Why do we do this? Why do we pull the id of a newly created record? There are a few reasons for this. One, so we can create our relationships correctly. Second, after seeding your database multiple times, the id of your records will always be incrementing since that’s how we set up our database. As you can see in the picture below, the id of our bears are 10
, 11
, and 12
. Dynamically creating our relationships instead of hardcoding in the id lets us not worry about messing with our seed files after they have been created.
With our seeder file ready to go, let’s go into the command line and execute our seeds.
We can also look into our database and see the new records.
Just like that, we now have records in our database. We can finally get to the fun part and show off the true power of Eloquent! Finally!
Next, we will go through all the types of queries you can create with Eloquent and we will see how easy it is to query databases with one-to-one and many-to-many relationships.
With migrations and seeding finally done, we’ll go through some basic real-world scenarios where we would need to access the information we’ve just put into our new database.
With Eloquent, it is that easy to create records for our database. Just call your model and the function you need. It is also incredibly easy to read, update, or delete records out of our database. Let’s look at CRUD functionality with Eloquent.
You’ve already seen how to create records since we used the ::create
method in our seeders.
In addition to the create method, you can also create a new object and assign different attributes to it. Once that is over you can call the save()
function.
Another method for creation is using firstOrCreate()
or firstOrNew()
. These will let us try to find a bear with certain attributes, if that bear is not found, then we will either create it into the database or instantiate a new instance.
We can build all of our queries simply. Select statements, get alls, and finding records are all doable and easy.
Here are a few examples of use cases.
First vs Get When querying the database and creating where
statements, you will have to use get()
or first()
. First will return only one record and get will return an array of records that you will have to loop over.
To update a record, just find the record you’d like to update, change the attributes, and save. Super simple!
Deleting records might be easier than updating records. There are two methods: pull the record you want and delete it or just use the destroy
method.
Now, this is where Eloquent gets fun. With most applications, you will have relationships amongst the parts of your database. We have already defined these: bears will have one fish and picnics will have many bears.
Let’s see how we can use Eloquent to query these relationships and get our bears something to eat! Since we defined the relationships in our models, querying will be incredibly easy.
For this example, let’s look at all the trees that our Lawly bear climbs.
For this example, we will get the picnics that our Cerms bear goes to. We can also get all the bears that go to the Yellowstone picnic.
As you can see, by setting up our Eloquent Models, we can easily query our database.
Let’s show all this off in an actual view file so we can see how we pass this data to our Laravel view. What good is all this work if we don’t show our users right?
We will need two things: a route and a view file. Let’s run through these quickly to show off all the great Eloquent things we just learned.
We will use Laravel Blade Templating to loop through our data and show it off in our view now. Let’s create our view file at app/views/eloquent.blade.php
.
Now when you go view your app in your browser at: http://example.com/eloquent
, you will see all the data being pulled from your database.
Well, that was a lot of information! Thanks for reading along and hopefully all this information has given you a good primer on how to use Eloquent for a real-world application. We’ve gone through:
While we have covered a good many topics, there is still so much more you can do when dealing with databases in your application. For more information, I always encourage reading through all the Eloquent docs. You can dive into things like pivot tables, polymorphic relationships, advanced querying, and so much more.
Also, for more reading on actual applications that use the database, check out our tutorial on Laravel CRUD with Resource Controllers.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!