Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

jcergolj/laravellte

216 stars
2 code files
View jcergolj/laravellte on GitHub

app/Scopes/VisibleToScope.php

Open in GitHub
use 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 GitHub
use App\Scopes\VisibleToScope;
use Illuminate\Foundation\Auth\User as Authenticatable;
 
class User extends Authenticatable
{
//
protected static function boot()
{
parent::boot();
static::addGlobalScope(new VisibleToScope());
}
//
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.