Book Image

Learning Laravel's Eloquent

By : Francesco Malatesta
Book Image

Learning Laravel's Eloquent

By: Francesco Malatesta

Overview of this book

<p>Learning Laravel's Eloquent starts off by taking you through setting up your first project and guiding you in creating a perfect Laravel environment. You will learn how to build the right database structure with the Migrations system and the Schema Builder class. Next, you will be introduced to the main element of Eloquent: the model. After treating the model as a single, isolated entity, you will learn how to create relations between them. You will be taken through organizing, filtering, and sorting your data with collections. You will then learn to enhance an application with new features using events and by creating new observers. Towards the end of the book, you will discover how to install, configure, and use the Eloquent ORM without Laravel. The book concludes by walking you through how to deal with complex problems and build advanced and flexible systems.</p>
Table of Contents (16 chapters)
Learning Laravel's Eloquent
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Query scopes


Query scopes are very funny and also powerful. I really like them because, like many programmers out there, I am absolutely and overwhelmingly lazy. I also have a great justification for my laziness: the Don't Repeat Yourself (DRY) principle.

In a few words, they let you reuse some logic in your queries. It is useful if you have similar queries in your application and you don't want to write them again and again every single time.

Let's take an example.

  <?php // Book.php

  namespace App;

  class Book extends Model {

      public function scopeCheapButBig($query)
      {
          return $query->where('price', '<', 10)->where('pages_count', '>', 300);
      }

  }

What happened? I declared a scopeCheaperButBig method. The scope prefix is used to specify that this is going to be used as a scope.

Now, how can I use a scope?

Here it is:

  <?php

  $bigAndCheaperBooks = \App\Book::cheapButBig()->get();

It is a cool feature. If you also think that you can split your...