Php 在门内使用数据库调用时发生Laravel错误
我在尝试将我的第一个Gate应用到我的Laravel项目中时遇到了一个问题。我注意到,我设置的路由Php 在门内使用数据库调用时发生Laravel错误,php,laravel-8,Php,Laravel 8,我在尝试将我的第一个Gate应用到我的Laravel项目中时遇到了一个问题。我注意到,我设置的路由map/{role}/{project}有可能让用户更改URL并访问他们不允许使用的角色/项目。我开始使用以下方法: AuthServiceProvider.php public function boot() { $this->registerPolicies(); Gate::define('isPermitted', function($
map/{role}/{project}
有可能让用户更改URL并访问他们不允许使用的角色/项目。我开始使用以下方法:
AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Gate::define('isPermitted', function($user, $role){
return DB::table('users')
->join('user_roles', 'users.id', '=', 'user_roles.user_id')
->join('roles', 'roles.id', '=', 'user_roles.role_id')
->select('roles.id')
->where('users.id', '=', $user->id)
->where('roles.id', '=', $role)
->first() ? true : false;
});
}
public function boot()
{
$this->registerPolicies();
Gate::define('isPermitted', function($user, $role){
return DB::table('users')
->join('user_roles', 'users.id', '=', 'user_roles.user_id')
->join('roles', 'roles.id', '=', 'user_roles.role_id')
->select('roles.id')
->where('users.id', '=', $user->id)
->where('roles.id', '=', $role->id)
->first() ? true : false;
});
}
MapController.php
public function index($role, $project)
{
$user = Auth::user() ?? 'null';
...
return dd(Gate::allows('isPermitted', $user, $role));
}
public function index($role, $project)
{
$user = Auth::user() ?? 'null';
...
return dd(Gate::allows('isPermitted', User::where('id', '=', $user->id), Role::where('id', '=', $role)->first()));
}
这将返回一个错误无效文本表示:7错误:整数的输入语法无效。出于某种原因,它试图在where语句的后半部分使用$user
而不是$role
,where语句应该是整数。在大门外进行此调用时不会发生此错误,在对用户对象中的DB结果和角色ID进行相同的调用时,返回DD的结果作为整数
我尝试的另一种方法是让Gate将模型作为参数,我做了以下工作
AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Gate::define('isPermitted', function($user, $role){
return DB::table('users')
->join('user_roles', 'users.id', '=', 'user_roles.user_id')
->join('roles', 'roles.id', '=', 'user_roles.role_id')
->select('roles.id')
->where('users.id', '=', $user->id)
->where('roles.id', '=', $role)
->first() ? true : false;
});
}
public function boot()
{
$this->registerPolicies();
Gate::define('isPermitted', function($user, $role){
return DB::table('users')
->join('user_roles', 'users.id', '=', 'user_roles.user_id')
->join('roles', 'roles.id', '=', 'user_roles.role_id')
->select('roles.id')
->where('users.id', '=', $user->id)
->where('roles.id', '=', $role->id)
->first() ? true : false;
});
}
Mapcontroller.php
public function index($role, $project)
{
$user = Auth::user() ?? 'null';
...
return dd(Gate::allows('isPermitted', $user, $role));
}
public function index($role, $project)
{
$user = Auth::user() ?? 'null';
...
return dd(Gate::allows('isPermitted', User::where('id', '=', $user->id), Role::where('id', '=', $role)->first()));
}
但是,这会导致以下错误:传递给App\Providers\AuthServiceProvider::App\Providers\{closure}()的参数1必须是App\Providers\User、App\Models\User的实例
但我不确定这意味着什么或如何修复它
哪条路是正确的?还是从Gate中删除DB调用更好