我有一个类型为Player且具有多个设备的用户
我想要一件设备,并在将用户返回给用户之前查看用户是否是它的所有者。如果他们不拥有它,他们将得到未经授权的回复
以下是我对模特的关系:
应用程序\ user.php的class User extends Authenticatable
{
protected $table = 'user';
public function player()
{
return $this->hasOne(Player::class);
}
}
应用程序\ Player.php
class Player extends Model
{
protected $table = 'player';
public function equipment()
{
return $this->hasMany(Equipment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
应用程序\ Equipment.php
class Equipment extends Model
{
protected $table = 'equipement';
public function player()
{
return $this->belongsTo(Player::class);
}
}
EquipmentController.php
我的尝试正在发挥......非常难看。
class EquipmentController extends Controller
{
public function show($id)
{
$equipment = Equipment::find($id);
if ( ! $equipment ) {
return 'Equipment does not exist');
}
// my attempt
$test = Equipment::with('player.user')->findOrFail($id);
if ($test->toArray()['player']['user']['id'] != Auth::user()->id){
return 'Unauthorized';
}
//
return $equipment;
}
}
有更简洁的方法吗?
我想在控制器中读取可读内容,如:
if(!$equipment->ownedBy(Auth::user())){
return 'Unauthorized';
}
或类似可读的东西。
一旦找到关系,我就不确定逻辑应放在何处。它应该在设备模型中吗? 任何帮助将不胜感激!
答案 0 :(得分:0)
在Equipment
模型中:
public function authorized()
{
return ($this->player->user->id == auth()->user()->id())
}
然后从您的控制器尝试:
$equipment->authorized() //returns true or false