我的应用程序确实有一个基于策略的权限管理,并且我使用 Nova 作为应用程序的后端。现在一切都在 nova 内部工作,我想为我的外部应用程序设置一个额外的 API。我确实必须覆盖indexQuery我的大部分资源,因为用户只能访问有限的范围,例如Customer资源: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);}
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
使用实时外观,您可以将应用程序中的任何类视为外观。
use Facades\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 AppCustomer::visibleToUser($query, $user);
}
- 1 回答
- 0 关注
- 116 浏览
添加回答
举报
0/150
提交
取消