Basics of laravel Eloquent for Beginners

Create, read, update, and delete operations basics

Every single article I read about Eloquent usually starts with some reading operations. I don’t like it. I will tell you how to create and insert new records, then we will fetch them with some reading operations.

No boring test inserts with some external administration tool.

Creating operations

Let’s create our first book! As a reference for the record structure, we will use the books table that we created in the previous chapter. The table has a very simple structure: a title, page count (pages_count), price, and description.

The procedure is as easy as creating an object.

Well, actually it is exactly the same. Create a new GET route in routes.php file under app/Http/, named book_create and type this:

  Route::get('book_create', function(){

    $book = new AppBook;

    $book->title = 'My First Book!';
    $book->pages_count = 230;
    $book->price = 10.5;
    $book->description = 'A very original lorem ipsum dolor sit amet...';


  });

If you think about it, there is something strange here! After checking the Model file, you can see that there are no title or pages_count properties declared. Among other things, Eloquent heavily uses magic methods. When the final query is built Laravel will use the names of the properties as the table columns to fill. Big deal!

Now, if you run this code and then check your table, you will not find any record yet. You must add a single final instruction: the save() method call.

  Route::get('book_create', function() {

      $book = new AppBook;

      $book->title = 'My First Book!';
      $book->pages_count = 230;
      $book->price = 10.5;
      $book->description = 'A very original lorem ipsum dolor sit amet...';

      $book->save();

  });

Execute it. Now, your book is saved on the database.

If you want, you can access a specific record field even after you’ve saved it. Let’s make another example.

  Route::get('book_create', function() {

      $book = new AppBook;

      $book->title = 'My First Book!';
      $book->pages_count = 230;
      $book->price = 10.5;
      $book->description = 'A very original lorem ipsum dolor sit amet...';

      $book->save();

      echo 'Book: ' . $book->id;

  });

Note

There is another little thing about Eloquent conventions; that is, every single table has an ID, autoincrementing a primary key.

Reading operations

Now that we’ve created some example records, why don’t we try to read them? An example is better than a thousand words.

  Route::get('book_get_all', function(){

    return AppBook::all();

  });

With a single instruction, here we are returning all the table records. The output is going to be very similar to this:

  [
    {
      id: 1,
      title: "My First Book!",
      pages_count: 230,
      price: "10.50",
      description: "A very original lorem ipsum dolor sit amet...",
      created_at: "2015-03-24 16:45:59",
      updated_at: "2015-03-24 16:45:59"
    }
  ]

Note

If you feel strange about this, don’t worry. If you return, in a route (or in a controller method) the results of an Eloquent model query, the results will be automatically transformed in JSON. It is a very useful shortcut if you are thinking about building a RESTful API.

Let’s create another book, to give our tests more elements.

    $book = new AppBook;

    $book->title = 'My Second Book!';
    $book->pages_count = 122;
    $book->price = 9.5;
    $book->description = 'Another very original lorem ipsum dolor sit amet...';

    $book->save();

After this, again execute your code in the book_get_all route. The result will be like this:

  [
    {
      id: 1,
      title: "My First Book!",
      pages_count: 230,
      price: "10.50",
      description: "A very original lorem ipsum dolor sit amet...",
      created_at: "2015-03-24 16:45:59",
      updated_at: "2015-03-24 16:45:59"
    },
    {
      id: 2,
      title: "My Second Book!",
      pages_count: 122,
      price: "9.50",
      description: "Another very original lorem ipsum dolor sit amet...",
      created_at: "2015-03-24 16:57:15",
      updated_at: "2015-03-24 16:57:15"
    }
  ]

However, we can do more. In fact, another great method is the find() method. You can use it like this:

  Route::get('book_get_2', function(){

      return AppBook::find(2);

  });

This method takes the primary ID as a parameter and returns the single record as an instance of the model.

Have a look at its output:

  {
    id: 2,
    title: "My Second Book!",
    pages_count: 122,
    price: "9.50",
    description: "Another very original lorem ipsum dolor sit amet...",
    created_at: "2015-03-24 16:57:15",
    updated_at: "2015-03-24 16:57:15"
  }

Note that this time you don’t have an array but a single object. These static methods, of course, aren’t all Eloquent has to offer. The cool part starts here.

Take a look at this:

  Route::get('book_get_where', function(){

      $result = AppBook::where('pages_count', '<', 1000)->get();
      return $result;

  });

You can use the where() method to filter your results. Then, after specifying your criteria, the get() method retrieves the results from the database. For a better understanding, imagine that the where() method is building a query. The get() method executes it. This last one is a trigger method.

If you just want to retrieve the first result instead of all of them, you can use the first() method instead of get().

  Route::get('book_get_where', function(){

      $result = AppBook::where('pages_count', '<', 1000)->first();
      return $result;

  });

Tip

Before we go any further, here’s a little reminder that can save you a lot of time. Actually, when you use trigger methods such as get() or first(), you can get two different kinds of results.

When you use first(), you are selecting a single instance. So, you will receive as a result (if present) a single instance of a certain model. Otherwise, if you are using all(), or get(), you will get a collection of instances.

Getting back to our where(), you can chain as many calls as you wish.

  Route::get('book_get_where_chained', function(){

      $result = AppBook::where('pages_count', '<', 1000)
              ->where('title', '=', 'My First Book!')
              ->get();

      return $result;

  });

You can iterate through results in a very simple way: simple for each is enough.

  Route::get('book_get_where_iterate', function(){

      $results = AppBook::where('pages_count', '<', 1000)->get();

      if(count($results) > 0)
      {
        foreach($results as $book){

            echo 'Book: ' . $book->title . ' - Pages: ' . $book->pages_count . ' <br/>';

        }
      }
      else
        echo 'No Results!';

      return '';
  });

The $results object is countable, so you can also check if you have results or not.

Have a look at this line:

  echo 'Book: ' . $book->title . ' - Pages: ' . $book->pages_count . ' <br/>';

You probably already noted that you can access a single record field in the same way as you did for setting them: magic methods.

Note

If you like it, you can access record fields like an array.

Try to switch $book->title to $book['title'] and see what happens.

Updating operations

Updating a record is as easy as creating it. To be honest, it is exactly the same thing with a single change in the first instruction.

  Route::get('book_update', function() {

      $book = AppBook::find(1);

      $book->title = 'My Updated First Book!';
      $book->pages_count = 150;

      $book->save();

  });

Instead of creating it, we are retrieving from the database the instance of the Model we desired. After that, using magic methods, we modified and then saved it. As happened for the insert procedure, the change you make becomes persistent after the save() call.

Deleting operations

Deleting a record is the simplest thing.

  Route::get('book_delete_1', function() {

      AppBook::find(1)->delete();

  });

Time to die, Book!

Note

Here’s a key concept. When you use the update() and delete() methods, you are working on a Model instance, just like you did before while creating it.

So, if you run a AppBook::find(1) instruction, you will get a Book class instance as a result. For some, it will be obvious, but many newcomers often have problems with this.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares