Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
net
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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:
A Bear model will correspond to a bears table in your database. Since we have convention 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
Super simple! There are many more applications of this and we'll get into them farther into this article.
Sample Application
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 2/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
(https://cask.scotch.io/2014/03/eloquent-bears.jpg)
Laravel Setup
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:
Those first two parts are easy enough so get those done. Then we'll work on migrating and seeding our
database.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 3/35
Creating Our Migrations
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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 (http://laravel.com/docs/migrations).
Migrations
Bears Migration
Let's create our migration. Through the command line, type:
// app/database/migrations/####_##_##_######_create_bears_table.php
...
$table string('name');
$table string('type');
$table integer('danger_level'); // this will be between 1-10
$table timestamps();
});
...
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.
Fish Migration
php artisan migrate:make create_fish_table --create=fish
// app/database/migrations/####_##_##_######_create_fish_table.php
...
$table timestamps();
});
...
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 .
Tree Migration
php artisan migrate:make create_trees_table --create=trees
// app/database/migrations/####_##_##_######_create_trees_table.php
...
$table string('type');
$table integer('age'); // how old is the tree
$table integer('bear_id'); // which bear climbs this tree
$table timestamps();
});
(https://bit.ly/2yyQv2e)
...
Picnic Migration
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.
// app/database/migrations/####_##_##_######_create_picnics_table.php
...
$table string('name');
$table integer('taste_level'); // how tasty is this picnic?
$table timestamps();
});
...
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.
Chris Sevilleja
php artisan migrate:make create_bears_picnics_table --create=bears_picnics
FOLLOW @CHRISONCODE(HTTPS://TWITTER.COM/I
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 8/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
$table integer('bear_id'); // the id of the bear
$table integer('picnic_id'); // the id of the picnic that this bear is at
$table timestamps();
});
...
Now we have a way to link our multiple bears to multiple picnics. This is how we create our many to
many relationship.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 9/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
(https://cask.scotch.io/2014/03/laravel-eloquent-migrating-database.png)
Eloquent Models
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.
Bear Model
Let's look at our Bear model first.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 10/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
// app/models/Bear.php
<?php
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 11/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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 (http://laravel.com/docs/eloquent#relationships) 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.
Fish Model
Here is our Fish model.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 12/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
// app/models/Fish.php
<?php
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 .
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 13/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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 .
Tree Model
// app/models/Tree.php
<?php
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 14/35
Picnic Model
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
You know the drill now. Let's make the Picnic model.
// app/models/Picnic.php
<?php
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 15/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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 (http://laravel.com/docs/eloquent).
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!)
// app/database/seeds/DatabaseSeeder.php
<?php
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 16/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
*
* Run the database seeds.
*
* @return void
// bear 2 is named Cerms. He has a loud growl but is pretty much harmless.
$bearCerms = Bear create(array(
'name' 'Cerms',
'type' 'Black',
'danger_level' 4
));
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 18/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
$this command info('The bears are alive!');
// we will use the variables we used to create the bears to get their id
Fish create(array(
'weight' 5,
'bear_id' $bearLawly id
));
Fish create(array(
'weight' 12,
'bear_id' $bearCerms id
));
Fish create(array(
'weight' 4,
'bear_id' $bearAdobot id
));
// we will create one picnic and apply all bears to this one picnic
$picnicYellowstone = Picnic create(array(
'name' 'Yellowstone',
'taste_level' 6
));
$picnicGrandCanyon = Picnic create(array(
'name' 'Grand Canyon',
'taste_level' 5
));
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 20/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
$bearAdobot picnics() attach($picnicYellowstone id);
$bearAdobot picnics() attach($picnicGrandCanyon id);
(https://synd.co/2QXW16X)
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 21/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
With our seeder file ready to go, let's go into the command line and execute our seeds.
(https://cask.scotch.io/2014/03/laravel-eloquent-migrating-database2.png)
We can also look into our database and see the new records.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 22/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
(https://cask.scotch.io/2014/03/laravel-eloquent-seeding-database1.png)
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 23/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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.
// create a bear
Bear create(array(
'name' 'Super Cool',
'type' 'Black',
'danger_level' 1
));
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.
// find the bear or instantiate a new instance into the object we want
$bear = Bear firstOrNew(array('name' 'Cerms'));
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 25/35
Getting and Finding Records
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
We can build all of our queries simply. Select statements, get alls, and finding records are all doable
and easy.
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 26/35
Updating Records
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
To update a record, just find the record you'd like to update, change the attributes, and save. Super
simple!
Deleting Records
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 27/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
// delete a record
Bear destroy(1);
Querying Relationships
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.
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 28/35
One to One Relationship
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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.
As you can see, by setting up our Eloquent Models, we can easily query our database.
Demonstration
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.
Our Route
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 31/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
// app/routes.php
...
// create our route, return a view file (app/views/eloquent.blade.php)
// we will also send the records we want to the view
// all the bears (will also return the fish, trees, and picnics that belong to the
with('bears', Bear all() with('trees', 'picnics'));
});
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 32/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
<!-- app/views/eloquent.blade.php -
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Eloquent Bears</title>
<!-- CSS -
<!-- BOOTSTRAP -
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.c
<style>
body { padding-top:50px; } add some padding to the top of our site
</style>
</head>
<body class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- BEARS -
<!-- loop over the bears and show off some things -
@foreach ($bears as $bear)
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 33/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
<h4>Trees</h4>
@foreach ($bear trees as $tree)
<p>{{ $tree type }}</p>
@endforeach
@endforeach
</div>
</body>
</html>
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.
Conclusion
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 34/35
10/20/2018 A Guide to Using Eloquent ORM in Laravel ― Scotch
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:
» Migrations
» Eloquent models
» Seeding
» Defining relationships
» Querying relationships
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 the all the
Eloquent docs (http://laravel.com/docs/eloquent). 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 (https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers).
www.akajlm.net
https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel 35/35