2016-03-04 137 views
0

我有一個用戶是類型的球員,有幾個設備Laravel 5.2嵌套雄辯關係

我想請求一臺設備,看看用戶是它的主人將其返回給用戶之前。如果他們不擁有它,他們將得到一個未經授權的響應

這裏有關係,我對型號:

應用程序\ 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

隨着我嘗試這是工作......菊st非常醜陋。

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

在你Equipment型號:

public function authorized() 
{ 
    return ($this->player->user->id == auth()->user()->id()) 
} 

然後從你的控制器,請嘗試:

$equipment->authorized() //returns true or false 
+0

這工作完全謝謝。只是另一個疑問,它是否從設備模型的[SRP](https://en.wikipedia.org/wiki/Single_responsibility_principle)中拿走?應該把它放在設備[策略](https://laravel.com/docs/5.1/authorization#policies)類中,並使用Gate類在控制器中授權它? – crwh05

+1

有很多方法可以解決這個問題。這只是一種方法。通過這種方式,您可以在應用中的任何位置使用此功能。即使在刀片視圖中。 –