Last active
July 19, 2017 17:20
-
-
Save cviebrock/01d28fd02ff3e755f0633564319894ce to your computer and use it in GitHub Desktop.
Programatically scoping Eloquent models ...?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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