-
app/Scopes/VisibleToScope.php
Open in GitHubuse App\Providers\AppServiceProvider; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Illuminate\Support\Facades\Schema; class VisibleToScope implements Scope { public function apply(Builder $builder, Model $model) { if (! auth()->hasUser()) { return $builder; } $user = auth()->user(); if ($this->returnEarly($user)) { return $builder; } if ($this->returnEarlyPermission($user, $model)) { return $builder; } return $builder->where(AppServiceProvider::OWNER_FIELD, $user->id); } public function returnEarlyPermission($user, $model) { $permission = $user->getPermission($model->getTable().'.index'); if (! $permission->pivot->owner_restricted === true) { return true; } if (! Schema::hasColumn($model->getTable(), AppServiceProvider::OWNER_FIELD)) { return true; } return false; } private function returnEarly($user) { if ($user === null) { return true; } if ($user->isAdmin()) { return true; } return false; } }
-
app/Models/User.php
Open in GitHubuse App\Scopes\VisibleToScope; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { // protected static function boot() { parent::boot(); static::addGlobalScope(new VisibleToScope()); } // }