---
title: "Discussion on \"A little trick with Eloquent query scopes that makes them super reusable\" | Hashnode"
description: "Discussion on \"A little trick with Eloquent query scopes that makes them super reusable\". STOP PRESS\nAs has been pointed out in the comments, using $query->withCalculatedPricing() should work. If it doesn't, make sure you are returning the Query Builder object from your scope. If you're getting an error or not the results you expect, chec..."
url: "https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [A little trick with Eloquent query scopes that makes them super reusable](https://hashnode.com/post/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable?utm_source=hashnode&utm_medium=feed)

STOP PRESS As has been pointed out in the comments, using $query->withCalculatedPricing() should work. If it doesn't, make sure you are returning the Query Builder object from your scope. If you're getting an error or not the results you expect, chec...

Jan 31, 2017 · hashnode.com  
Updated Feb 3, 2017  
Read the article

-   [#laravel](https://hashnode.com/tag/laravel)
-   [#eloquent](https://hashnode.com/tag/eloquent)
-   [#query-scopes](https://hashnode.com/tag/query-scopes)
-   [#php](https://hashnode.com/tag/php)

## Written by

[Simon Hamp](https://hashnode.com/@simonhamp)

@simonhamp · Las Palmas, Gran Canaria

  
[View profile](https://hashnode.com/@simonhamp)

Code isn't everything. Live

I'm a full-stack web developer who is enjoying the PHP renaissance. I love building apps with web technologies.

## Responses 5

Markdown supported · ⌘↵ to post

[David](https://hashnode.com/@dbw)

[Feb 1, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/5891cef0cfe48c4f6b113b48)

I've been using scopes inside with clauses etc for a very long time, I don't think this is needed. I believe it is not working for you simply because you are not returning the $query object from the scope, it should be:

```
public function scopeWithCalculatedPricing( $query, $include_tax = false ) {
  $tax_multiplier = $include_tax ? 1.2 : 1;
  return $query->selectRaw( 'products.*, ( products.price * ' . $tax_multiplier . ' ) as total_price' )
      ->where( 'stock', '>', 0 );
}
```

Please note the added **return**. If you can see if you refer to the laravel docs on the subject: [https://laravel.com/docs/5.4/eloquent#local-scopes](https://laravel.com/docs/5.4/eloquent#local-scopes)

[Simon Hamp](https://hashnode.com/@simonhamp)

[Feb 3, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/5891cef0cfe48c4f6b113b48#reply-5894532a1854daa217ca56d8)

> This is actually very incorrect

Well, no, it wasn't incorrect, it just wasn't as specific as you correctly note.

I completely agree with your summation and I'll concede to anyone who knows far more about the inner workings of Eloquent than me. Indeed, that is how I'd hoped things would work.

However, when I tried to get this to work originally I was getting a `Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string` error for some reason. I hadn't explored this error to find out what was causing it. But it seems _that_ was because of the lack of a return.

After @dbw 's comment, I added the return and tried again, but I was still getting an error. I can only assume that I attempted this so hastily that I didn't spot another error.

Following your comment, I've tried this code again and I am now getting the desired result.

I hang my head in shame and bow to your greatness. Clearly, I need to fact-check my stories more thoroughly in future!

Thank you for taking the time to write a considered response.

[Eric Tucker](https://hashnode.com/@tucker_eric)

[Feb 3, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/5891cef0cfe48c4f6b113b48#reply-5894cb7ef4fe73f5da76c825)

Of course! One of the reasons I love Eloquent is because it is very intuitive and there was a lot of work put in behind the scenes to lower that barrier to entry for those new to Laravel or even PHP in general. If I can give advice to anyone working with Eloquent it's that if the steps you're taking to achieve what you're trying to do seem repetitive or unnecessary, they probably are. If something seems too complicated then you're probably over thinking it.

100% of my development knowledge came from the open source community and people like you that take time out of their schedules to write articles and documentation for people to learn. Keep up what you're doing and know that the lurkers are appreciative of your contributions. Right or wrong way, we learn them all to become better at our craft. In fact, I learn more from every mistake I have made and bug I have introduced than I have from copying and pasting code from github.

Keep up the writing and feel free to reach out to me for any reason.

Cheers!

[Simon Hamp](https://hashnode.com/@simonhamp)

[Feb 6, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/5891cef0cfe48c4f6b113b48#reply-5898d5230ff2cedd1c336e2a)

Agreed. My ego was saying "delete the post and remove all traces", but I think it's actually more valuable to me (and maybe others) if I just leave this here.

[Imran Ali](https://hashnode.com/@imranali)

[Feb 3, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/589428373285e912dbbb18ea)

@simonhamp This is exactly what I was looking for couple of weeks back.

I posted this problem on StackOverflow as well but didn't get any answer.

[stackoverflow.com/questions/41654506/laravel-5-2-…](http://stackoverflow.com/questions/41654506/laravel-5-2-eloquent-query-with-local-scope)

I'll give it a try.

Thanks a lot :)

[Simon Hamp](https://hashnode.com/@simonhamp)

[Feb 3, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/589428373285e912dbbb18ea#reply-58944b16f7b7dab3f917eb45)

Cool :) Look forward to hearing how you get on.

[Emil Moe](https://hashnode.com/@emilmoe)

[Feb 1, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/589144cba9cd4266f9d0bdc8)

I admit I was too lazy to read it all at 03.15am, but just before I dig in (and it will also be a reminder to read it tomorrow if I have a notification :)), what is your benefit from `protected static` over the regular `public`?

[Simon Hamp](https://hashnode.com/@simonhamp)

[Feb 1, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/589144cba9cd4266f9d0bdc8#reply-5891be5280f6cd584cfca63c)

Hopefully, when you read through, you'll see what's happening... we're actually leaving the conventional scope method as it is (`public`), but we're adding a new `protected` instance method (not `static`) and calling that from our scope instead.

This then lets us use the magic methods to access our `protected` method from a static and external context, allowing the 'scope' to be used inside a constrained, eager-loaded relationship subquery.

[Matteo Orefice](https://hashnode.com/@MatteoOreficeIT)

[Mar 22, 2018](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/5ab37d475bb4ae0c73d075bd)

When you need to call this **kind of shared protected methods** from the **same class `boot` method**, for example to be reused in a **global scope** an error occurs like this :

> Non-static method App\\Product::withCalculatedPricingScope() should not be called statically

but you can avoid it with this useful trick

```
if ( ! function_exists('outer_scope')) {

    class guestClass23c7d2389d6839b0dcd53a8230d04b35{};
    /**
     * Easily changes closure scope to an extraneous
     *
     * @param $closure
     * @param null $thisPointer
     * @param string $scope
     * @return mixed
     */
    function outer_scope($closure,$thisPointer=null,$scope=\guestClass23c7d2389d6839b0dcd53a8230d04b35::class){
        return $closure->bindTo($thisPointer,$scope);
    }
}

// Reuse as global scope
class Product {
    // ....
    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        self::addGlobalScope(outer_scope(function($query){
            Product::withCalculatedPricingScope($query);
        }));
    }
    // ....

    // Our actual scope, which will continue to work in exactly the same way as before
    public scopeWithCalculatedPricing( $query, $include_tax = false ) {
       $this->withCalculatedPricingScope( $query, $include_tax );
    }

    protected function withCalculatedPricingScope( $query, $include_tax = false ) {
        $tax_multiplier = $include_tax ? 1.2 : 1;
        $query->selectRaw( 'products.*, ( products.price * ' . $tax_multiplier . ' ) as total_price' )
                   ->where( 'stock', '>', 0 );
    }

}
```

[InstanceOfMichael](https://hashnode.com/@IOM)

[Sep 16, 2017](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/59bc85fcd692facd74b6f4a3)

I've been thinking about this problem for a few years and I'd like to propose another solution. (and perhaps my problem is not literally the same).

What if we used seperate invokable classes instead of query scopes on the Model class?

In this example:

```
class Bee extends Eloquent {
    public function scopeAlive($query) {
         $query->where('is_alive', true);
    }
}

class Hive extends Eloquent {
}

// get all hives with live bees
Hive::query()->whereIn('hives.id', Bee::query()->alive()->pluck('hive_id')->all())->get()
// this works, but produces 2 SQL queries
// we must fulfill our unnatural desires to micro-optimize this prototype
// of a bee hive health tracking SASS

Hive::query()->whereIn('hives.id', function($query) {
    $query->from('bees')
        //->alive() // scope not found!!
        // Bee::scopeAlive($query) // this one crashes, too!
        ->select('bees.id')
        ->where('bees.is_alive', true); // oh no, I had to copy and paste the contents of Bee->scopeAlive!
        // a real world scenario that I actually care about would be when scopeAlive is a more complicated sub-operation
        // but you can see that scopes are not composable or flexible
})->get()

// introducing the invokable class!
class BeesAlive () {
    public function __invoke($query) {
        $query->where('bees.is_alive', true);
    }
}

// Now you can write

Bee::query()->where(new BeesAlive)->paginate();
Hive::query()->whereIn('hives.id', function($query) {
    $query->from('bees')
        ->select('bees.hive_id')
        ->where(new BeesAlive);
})->get();

// Now to add fluff to it:
class BeesAlive () {
    protected $foreignKey

    public function __construct($foreignKey) {
        $this->foreignKey = $foreignKey;
    }
    public function __invoke($query) {
        if ($this->foreignKey) {
            $query->from('bees')
                ->select($this->foreignKey);
        }
        $query->where('bees.is_alive', true);
    }
}

// now we can do this:
Bee::query()->where(new BeesAlive)->paginate();
Hive::query()->whereIn('hives.id', new BeesAlive('bees.hive_id'))->get();
// woah! one query! that's at least 10 milliseconds!

// Now we can gold plate our controller:

// in controller:
Hive::query()->where(new HiveFilters($request->all()))->get()

// literally anywhere else
class HiveFilters {
    protected $arr;
    protected $foreignKey;
    public function __construct(array $arr, $foreignKey) {
        $this->arr = $arr;
        $this->foreignKey = $foreignKey;
    }
    public function __invoke($query) {
        if ($this->foreignKey) {
            $query->from('hives')
                ->select($this->foreignKey);
        }
        foreach($this->arr as $key => $value) {
            if ($key === 'bees' && is_array($value)) {
                // pretend like we defined this class:
                $query->whereIn('hives.id', new BeesFilter($value, $foreignKey = 'bees.hive_id'));
                // if bees.is_alive was specified in the search for hives,
                // we'll only get hives that have live bees
                // not only that, but you can now use the word "composable"
                // an inappropriate number of times to your lead dev
            } else {
                // more logic, map to other filters
            }
        }
    }
}
```

Thoughts?

[Matteo Orefice](https://hashnode.com/@MatteoOreficeIT)

[Mar 22, 2018](https://hashnode.com/posts/a-little-trick-with-eloquent-query-scopes-that-makes-them-super-reusable/5890be485478d2f4f656800e/comment/59bc85fcd692facd74b6f4a3#reply-5ab379d95bb4ae0c73d0759d)

It would be very but ... in Laravel 5.4 where accepts as first parameter a string or a Closure, and so :

```
(new BeesAlive instanceof \Closure) != true
```
