1
votes

Regarding Scope Queries, is it intended behavior that returning any falsey value will result in an Eloquent\Builder being returned?

If I return any non-falsey value (say a number, string, array, etc) it will return the actual value (be it a number, string, array, etc) but if I return false, 0, null it always returns an Eloquent\Builder.

Is there a way to work around this, and return the correct type when a falsey instead of a object of type builder?

Abstracted Test Case

In Model

class MyModel extends Eloquent
{
  public function scopeTestFalse{
    return 0;  
  }
  public function scopeTestTrue()
  {
    return 99;  
  }

}

In Route

var_dump(MyModel::scopeTestFalse()); // object(Illuminate\Database\Eloquent\Builder)
var_dump(MyModel::scopeTestTrue()); // int(99)
1
have you declared those functions as static ? the above example works fine for me, using laravel 4.1 on PHP 5.3.27cecilozaur
They're not static. When you say it works fine, what does scopeTestFalse return?Chris
int(0) the other one returns int(99), make sure to declare all functions static because Eloquent implements the __callStatic() function (which gets triggered whenever you try and access a static method that's not part of the class you are calling). Hope this makes sense.cecilozaur
Scopes aren't meant to be static. Also, you can drop the "scope" portion when calling them - part of Laravel's magic. IE: MyModel::testFalse(); If you aren't manipulating a relationship or query object however you might look at simply making these a function and not a scope - which bypasses some of the magic used to chain query objects.Abba Bryant
@AbbaBryant This is the correct answer, scopes aren't meant to be static and should only act on relationships/queries. Please change your comment to an answer, and I will mark it correctChris

1 Answers

2
votes

Scopes aren't meant to be static. Also, you can drop the "scope" portion when calling them - part of Laravel's magic. IE: MyModel::testFalse(); If you aren't manipulating a relationship or query object however you might look at simply making these a function and not a scope - which bypasses some of the magic used to chain query objects.