Может быть, вопрос не совсем ясен, но я нашел решение:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Auth;
use App\User;
class DataAccessScope 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)
{
// find the actual user
$user_id = Auth::user()->id;
$user = User::find( $user_id );
// get all employees
$employees = $user->allEmployeeFlatten();
// get only the employee's ids
$user_ids = $employees->pluck('id');
// add current user's id too
$user_ids->push( $user_id );
// add the condition to every sql query
$builder->whereIn('user_id', $user_ids);
}
}
Вот функция allEmployeeFaletten()
User
модели:
public function allEmployeeFlatten() {
$employees = new Collection();
foreach ( $this->employee()->get() as $employee ) {
$employees->push( $employee );
// run only if the user is on a leader level
if ( $employee->user_role_id != 5 ) {
$employees = $employees->merge( $employee->allEmployeeFlatten() );
}
}
return $employees;
}
Эта областьдобавляйте условие ко всем SQL-запросам каждый раз, когда я использую область.