Raviya Technical
Published in

Raviya Technical

Laravel Advance | Global Scope

<?phpnamespace App\Scopes;use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class ActiveScope implements Scope{/*** 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){$builder->where('is_active', '=', 1);}}
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;
use App\Scopes\ActiveScope;
class User extends Model{protected $fillable = ['name','email','password','is_active',];protected static function boot(){parent::boot();static::addGlobalScope(new ActiveScope);}}
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;
use App\Scopes\ActiveScope;
class Admin extends Model{protected $fillable = ['name','email','password','is_active',];protected static function boot(){parent::boot();return static::addGlobalScope(new ActiveScope);}}
$users = User::select('*')->get();$admins = Admin::select('*')->get();
$users = User::select('*')->withoutGlobalScope(ActiveScope::class)->get();$admins = Admin::select('*')->withoutGlobalScope(ActiveScope::class)->get();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store