我确实为我的应用程序提供了基于策略的正确管理,并且我正在使用Nova作为应用程序的后端。
现在一切都在nova内部工作,我想为我的外部应用程序设置一个额外的API。
我确实必须覆盖我的大部分资源,因为用户只能访问有限的范围,例如资源:indexQueryCustomer
public static function indexQuery(NovaRequest $request, $query)
{
$user = Auth::user();
// Admins and office users can see all customers
if($user->authorizeRoles(['admin', 'office'])) {
return $query;
}
// A user can only see customers associated with a job they work on
$query
->select('customers.*')
->join('jobs', 'jobs.customer_id', '=', 'customers.id')
->join('teams', 'jobs.team_id', '=','teams.id')
->join('team_user', 'teams.id', '=', 'team_user.team_id')
->where('team_user.user_id', '=', $user->id);
return $query;
}
现在对于API,我基本上需要相同的范围,我想知道把这个代码放在哪里。我的第一个想法是向模型添加一个作用域,所以我会添加一个带有参数的作用域:Customer
/**
* Limit the results to the customers the user is able to see
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \App\User $user
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeVisibleToUser($query, $user) {
if($user->authorizeRoles(['admin', 'office'])) {
return $query;
}
// A user can only see customers associated with a job they work on
$query
->select('customers.*')
->join('jobs', 'jobs.customer_id', '=', 'customers.id')
->join('teams', 'jobs.team_id', '=','teams.id')
->join('team_user', 'teams.id', '=', 'team_user.team_id')
->where('team_user.user_id', '=', $user->id);
return $query;
}
有没有办法在不创建虚拟客户对象的情况下应用方法中的作用域?indexQuery
use App\Customer as AppCustomer;
/**
* Build an "index" query for the given resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public static function indexQuery(NovaRequest $request, $query)
{
$user = Auth::user();
return (new AppCustomer())->scopeVisibleToUser($query, $user);
}
慕田峪7331174