Understand Query scopes in laravel

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.

Recommended :  Uploading an image using Redactor in laravel

Now, how can I use a scope?

Here it is:

  <?php

  $bigAndCheaperBooks = AppBook::cheapButBig()->get();

It is a cool feature. If you also think that you can split your logic in a more intelligent way, you can do it as follows:

  <?php // Book.php

  namespace App;

  class Book extends Model {

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

      public function scopeExpensive($query)
      {
      return $query->where('price', '>', 100);
      }

      public function scopeLong($query)
      {
        return $query->where('pages_count', '>', 700);
      }

      public function scopeShort($query)
      {
      return $query->where('pages_count', '<', 100);
      }

  }

Use it accordingly, reducing repeated code.

  <?php

    // getting cheaper and longer books;
    $cheapAndLongBooks = AppBook::cheap()->long()->get();

    // getting most expensive and longer books;
    $expensiveAndLongBooks = AppBook::expensive()->long()->get();

    // getting cheaper and shorter books;
    $cheapAndShortBooks = AppBook::cheap()->short()->get();

    // getting expensive and shorter books;
    $expensiveAndShortBooks = AppBook::expensive()->short()->get();

If you need it, you can also define dynamic scopes in order to pass parameters to your scopes. If you like it, calling a scope inside another is not a problem.

  <?php // Book.php

  namespace App;

  class Book extends Model {

    public function scopeLong($query)
      {
        return $query->where('pages_count', '>', 700);
      }

      public function scopeLongAndCheaperThan($query, $amount)
      {
          return $query->long()->where('price', '<', $amount);
      }

  }

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