How To Get Started With Eloquent In Laravel

How To Get Started With Eloquent In Laravel

Eloquent makes use of the Active Record pattern adored by software developers far and wide. Active Record was originally named by the software developer Martin Fowler when he discussed it in his book titled Patterns of Enterprise Application Architecture. It is a pattern where an Object maps to a table in a database. The object’s properties usually correspond to the columns in the given table. It’s a convenient and easy to use pattern, and Eloquent is a great version of active record. Let’s take it for a test drive on our games table now!

Let’s Talk About Models

We’ve already taken the Query Builder for a quick spin around the block, and it works great. Now we are going to look at Eloquent and see how we can use that to interact with the database. When using Eloquent, we’ll be making use of Models. In the MVC or Model View Controller pattern, the model takes the responsibility of maintaining and managing the data in an application. You may wonder then, why do I sometimes here people refer to them as Models in the plural when talking about a given system. This is because just as your database has many tables, your application may have many models. In Eloquent, you will have one Model per Database table. We have been working with the concept of maintaining a repository of games during this tutorial series. We already have a games table, so why not make a Model to correspond to that table? First off let’s get some help.
php artisan help make model

A Model is the singular version of the database table it represents

Let’s go ahead and create a Game model now.
php artisan make model game

Models live in the app directory. Notice we now have a file named Game.php which is the model we just created.
model in phpstorm


The Game class extends the Eloquent Model class.

Graduating From Query Builder to Eloquent

Now that we have a model, we can make use of it. Let’s grab that routes file from our getting started with query builder tutorial, and change it up to make use of our new Eloquent model.

This snippet gets all of the games in the database as a collection, just like in our query builder tutorial.

Importing The Namespace

App\Game::all(); is some pretty terse syntax. We can make it shorter though! Let’s import the namespace and then shorten up our call to the database to simply Game::all();

Finding a Specific Record with Eloquent

We can find a record by it’s id with the find() method. Our files from the query builder tutorial are now both updated to use Eloquent, and everything is still working correctly.

laravel in action

Practicing Eloquent Queries Using Tinker

Having a way to easily test snippets of code is really helpful. With JavaScript, you simply open Chrome Developer Tools, and you can try out simple expressions right in the console. With PHP, you need to save your file and then reload your browser. We’ve covered a couple of ways to test PHP to get around this. Let’s look at how to use Tinker to practice making Eloquent Queries.

Navigate to the root directory of your project in the terminal and type php artisan tinker. You’ll be greeted with something like Psy Shell v0.8.3 (PHP 7.1.2-3+deb.sury.org~xenial+1 รข cli) by Justin Hileman, and a prompt consisting of three greater than symbols. You are now in a REPL for PHP.
eloquent queries using tinker

Insert New Records With Eloquent

One of my favorite use cases for Eloquent is to insert new records into the database. It is very simple to do. Check it out.
insert new record into database using eloquent
By simply typing new Game;, a new instance of our Game Model is created. Remember that our games table has several columns. Let’s recall what they are.
describe mysql table from console
Columns are also called Fields. So we can see fields of id, title, publisher, releasedate, created_at, and updated_at. Here is what is so cool. Those fields in the database table map directly to property names on the Model object! What that means is that we can simply assign values to them, just as we would any other object in PHP. When you’re finished assigning values, all you have to do is call the save() method on the object, and the data is saved right into that table. So Cool! Let’s add another game.
adding records to database eloquent tinker
Now you might be wondering why we did not have to worry about the id or timestamp fields. This is because these fields are handled automatically in the database or by Eloquent. The id field is an auto increment field, which means it’s value will go up by one every time a new record is added to the database. This way, every single record in the database will have it’s own unique id. MySql takes care of this for us. The timestamps are handled automatically by Eloquent, so we’ll never have to manually set those.

Let’s look at all the games again. This time, we’ll just update our routes file so that we can inspect them. We’ll also give ourselves some ideas on how to add constraints to the query to get specific games from the database.

Get all the records with all();

How Eloquent Works

One thing to note here is that the way Eloquent, or any other tool used to work with a database works, is that it generates the SQL queries for you. So even though you simply type something like Game::all(), behind the scenes, the database is getting queried with SQL. For this particular query, it is select * from games;. With that said, lets’ now try a few different queries to get a particular game or set of games.

Various Ways To Retrieve or Select Data

We’ll list out the Eloquent command and the resulting SQL query for reference.

Getting Specific Records Using where()

The where clause takes three arguments in the form of where(‘field’, ‘operator’, ‘value’). The first argument is the field, or column, of the table you are concerned with. In our example that means we’re looking to get records that have a particular trait in the id, title, publisher, or releasedate fields. The second argument is the operator. These are things like =, >, >=, <, <=, !=, like, not like, regexp, in, not in, between, not between, is null, is not null, etc... The argument is the value you want to compare against, operate on, or generally work with. Let's get all games that have an id that is greater than 3.

  • select * from games where id > ‘3’;
  • If you look at the id’s of the two results returned, we can see both of them have a value which is larger than 3. So our query worked!

    How about getting a game which has the word Mega in the title. Coming right up.

  • select * from games where title like ‘%Mega%’;
  • How about all games that have a publisher of Nintendo.

  • select * from games where publisher = ‘Nintendo’;

  • Let’s get the games have a releasedate of 1989.

  • select * from games where releasedate = ‘1989’;
  • So this is pretty cool. We have a good understanding of where( ) and how to make use of it, and make use of it you will. All the time!

    Order Query Results Using orderBy( )

    orderBy() can be applied to Eloquent queries to order the results by a particular field in the table. By default, orderyBy() sorts the results in ascending order. If you pass the optional second argument with a string of ‘desc’, you can sort the results in descending order. Let’s try an example.

    Order all games by the id field in descending order.

  • select * from games order by id desc;

  • Limiting The Number of Results with take(), and introducing command chaining

    Limiting the number of results a particular query should return is a very common operation. In Eloquent, we can make use of the take() command and pass it a number value to represent the number or records we want. In addition, we will show an example of chaining commands together. This is what’s known as a fluent interface. Let’s see an example here.

    Get three records ordered by their releasedate in descending order.

  • select * from games order by releasedate desc limit 3;

  • Retrieving Multiple Records of a single field in a table with pluck( )

    If you only want a specific field from the table, you can use pluck() like so.

  • select title from games;

  • Queries don’t run until you call get()

    Let’s add a couple of more games into the database to demonstrate what we mean by this.
    insert new records using eloquent

    Now, what we are going to do is set up a basic eloquent query without calling get() and assigning the result to a variable. An instance of Illuminate\Database\Eloquent\Builder is assigned to that variable. What this means is that you can then add commands to that instance one at a time, as you see fit. When you’re ready to actually trigger the query, you can then call get(). Let’s see this idea in practice.
    how to build up a query in eloquent
    So you can see that when we write something like $game = Game::where(‘publisher’, ‘=’, ‘Nintendo’); – we are putting an instance of the query builder into the $game variable. We can then call additional commands on that variable. This is a process of ‘building up’ a query so to speak. When you’re ready to execute the query, you just call $game->get(); to fire it off. For this getting started tutorial, this concept is not critical. When you start getting into advanced Eloquent, this becomes more important.

    The query above is the same as if it were written like so:

    select * from games where publisher = ‘Nintendo’ order by releasedate desc limit 3;

    Introduction to Query Scopes

    What if I told you, you could type something like Game::nintendo()->get(); and have all the games by Nintendo retrieved out of the database? Well, I’m telling you that, so let’s see how we can do this!

    Open up the Games.php Model, and add the following code.


    Let’s try it out right in our / route.

    query scope example in laravel eloquent

    Well, well, well! That does indeed look pretty cool! So to create a query scope, you do the following.

    • Create a new public function in your Model class
    • Name the scope whatever you like starting with a capital letter, and prefixed with the word scope, all lower case.
    • The function accepts the $query as an argument
    • The function returns the $query with your chosen logic applied

    Query Scopes Can Be Used Fluently

    We can see that a query scope is a nice way to create a nice terse name as a wrapper around longer logic for a query. This is perfect for longer queries that you anticipate using many times in your application. Another nice benefit of query scopes is that you can use them fluently just like any other command in the query builder. For example, let us use our new Nintendo query scope, but also we only want Nintendo games that have the word Mario in their title. Let’s try this out.

    query scope example with additional constraints
    Now that is what I call Cool and the GANG!

    Updating a Model

    It’s quite easy to update a record in the database using Eloquent. You just find the model, assign any new value to it’s properties, then save. Let’s see how.
    update a record in database table with eloquent

    Deleting a Model

    There are a few ways to delete records in the table. Here we delete a single game by it’s id. We then delete multiple games at once based on the name of the publisher.
    deleting records using eloquent

    How To Get Started With Eloquent In Laravel Summary

    What a fun review of how to get your feet wet with Eloquent. We covered a lot of good topics in this tutorial, and to be fair, there is a ton more to know. This gets us going on the right track however, and the real foundation level stuff was covered here. So what did we learn?

    • Models Manage Data in your application
    • Eloquent is a beautiful implementation of Active Record
    • One Model or Eloquent Class per Database Table
    • Use php artisan make:model Name to create your Model
    • Model Name is typically Singular
    • Database Table is typically Plural
    • Simplifies Database Interaction
    • You can practice Eloquent Queries using Tinker
    • You are awesome