Skip to content

Instantly share code, notes, and snippets.

@vuthaihoc
Created April 12, 2022 13:53
Show Gist options
  • Save vuthaihoc/c636b91d28742806921b231bbe0398c0 to your computer and use it in GitHub Desktop.
Save vuthaihoc/c636b91d28742806921b231bbe0398c0 to your computer and use it in GitHub Desktop.
Scope with extensions
<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class CountryScope implements Scope
{
protected $extensions = ['WithCountry', 'WithAnyCountry', 'WithCountries'];
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$country = config('app.country');
if(!$country){
throw new \Exception("app.country must be set");
}
$builder->where('country', $country);
}
public function extend(Builder $builder)
{
foreach ($this->extensions as $extension) {
$this->{"add{$extension}"}($builder);
}
}
protected function addWithCountry(Builder $builder){
$builder->macro('withCountry', function (Builder $builder, $country) {
return $builder->withoutGlobalScope($this)->where('country', $country);
});
}
protected function addWithAnyCountry(Builder $builder){
$builder->macro('withAnyCountry', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
}
protected function addWithCountries(Builder $builder){
$builder->macro('withCountries', function (Builder $builder, ...$countries) {
return $builder->withoutGlobalScope($this)->whereIn('country', $countries);
});
}
}
<?php
namespace App\Models\Traits;
use App\Models\Scopes\CountryScope;
/**
* @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withCountry(string $country)
* @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withAnyCountry()
* @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withCountries(string ...$countries)
*/
trait CountryHelper
{
public static function bootCountryHelper()
{
static::addGlobalScope(new CountryScope());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment