Query Scopes
Global scopes allow you to add constraints to all queries for a given model.
Local Scopes
Local scopes allow you to define common sets of query constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with scope.
//Post Model
use Roddy\FirestoreEloquent\Facade\FModel;
use Roddy\FirestoreEloquent\Firestore\Eloquent\Traits\FRelations;
class Post extends FModel
{
//Import this class
use FRelations;
protected $collection = 'posts';
protected $primaryKey = 'post_id';
protected $fillable = ['title', 'content', 'user_id'];
//Local Scope
public function scopePopular($query)
{
return $query->where(['likes', '>', 100]);
}
}
Utilizing a Local Scope
Once the scope has been defined, you may call the scope methods when querying the model. However, you should not include the scope prefix when calling the method. You can even chain calls to various scopes:
use App\FModel\Post;
//Find popular posts
$popularPosts = Post::popular()->get();
Dynamic Scopes
Sometimes you may wish to define a scope that accepts parameters. To get started, just add your additional parameters to your scope method's signature. Scope parameters should be defined after the $query parameter:
//User Model
namespace App\FModels;
use Roddy\FirestoreEloquent\Facade\FModel;
use Roddy\FirestoreEloquent\Firestore\Eloquent\Traits\FRelations;
class User extends FModel
{
/**
* Scope a query to only include users of a given type.
*/
public function scopeOfType($query, string $type)
{
return $query->where(['type', $type]);
}
}
Once the expected arguments have been added to your scope method's signature, you may pass the arguments when calling the scope:
//Find users of a given type
$users = User::ofType('admin')->get();
//OR
$users = User::ofType('admin')->orWhere(['age', '>', 30])->get();