Skip to content

Instantly share code, notes, and snippets.

@cviebrock
Last active July 19, 2017 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cviebrock/01d28fd02ff3e755f0633564319894ce to your computer and use it in GitHub Desktop.
Save cviebrock/01d28fd02ff3e755f0633564319894ce to your computer and use it in GitHub Desktop.
Programatically scoping Eloquent models ...?
<?php
class PostService {
/**
* @param array $scopes
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function buildScopedQuery(array $scopes = []): Builder
{
$query = Post::newQuery();
foreach ($scopes as $scope) {
if (is_string($scope)) {
$query->{$scope}();
} else {
$parameters = $scope;
$scope = array_shift($parameters);
$query->{$scope}(...$parameters);
}
}
return $query;
}
}
<?php
$postService = new PostService; // or whatever via DI, etc.
$posts = $postService->buildScopedQuery([
'popular',
'active',
['ofType','admin']
])->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment