簡體   English   中英

如何在Laravel 5.3中執行授權策略?

[英]How can I do Authorization Policies in Laravel 5.3?

我在這里讀到: https : //laravel.com/docs/5.3/authorization#writing-policies

我試圖喜歡

我的FavoritePolicy是這樣的:

<?php
namespace App\Policies;
use App\User;
use App\Models\Favorite;
use Illuminate\Auth\Access\HandlesAuthorization;
class FavoritePolicy
{
    use HandlesAuthorization;
    public function view(User $user, Favorite $favorite)
    {
        return $user->id === $favorite->user_id;
    }
}

我的FavoriteController是這樣的:

<?php
use App\Models\Favorite;
...
class FavoriteController extends ApiController
{
    ...
    public function index(Favorite $favorite)
    {
        $this->authorize('view', $favorite);
        return view('profile.favorite');
    }
}

我的AuthServiceProvider是這樣的:

<?php
namespace App\Providers;
use App\Models\Favorite;
use App\Policies\FavoritePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Favorite::class => FavoritePolicy::class,
    ];
    public function boot()
    {
        $this->registerPolicies();
    }
}

當我運行系統以顯示收藏夾列表時,存在如下錯誤:

哎呀,看起來像出事了。

Handler.php第115行中的1/1 HttpException:此操作是未授權的。

什么是授權策略實施正確?

我在視圖方法(FavoritePolicy)中嘗試dd($user) ,結果顯示正在記錄用戶數據。 這是真的

但是我嘗試了dd($favorite) ,結果沒有顯示當前登錄用戶的收藏夾數據。 我在表上檢查時,存在當前登錄用戶的收藏夾數據

我怎么解決這個問題?

更新資料

結果為dd($favorite)

Favorite {#498 ▼
  #fillable: array:3 [▶]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
}

感謝您提供更新中的其他信息!

因此,您只想顯示一個特定Favorite實體的詳細信息頁面,但前提是用戶是該實體的所有者?

首先是一個小的“問題”:通常在Laravel中,顯示特定實體詳細信息的控制器方法稱為show ,而不是index index是顯示實體列表(在您的示例中:收藏夾列表)的方法的名稱。

關於您的問題:
您的政策會檢查當前登錄的用戶是否可以查看空的$favorite (請參見更新后的dd($favorite)輸出)。 這意味着,您的index方法中也未設置$favorite

我想,您定義的路由與此類似:

Route::get('favorite/{id}', 'FavoriteController@index');

這意味着, id的值作為參數而不是Favorite實體注入到index方法中。 要查詢“ Favorite實體,您需要在方法中進行操作。

因此,您的方法應如下所示:

public function index($favoriteId)
{
    $favorite = Favorite::findOrFail($favoriteId);
    $this->authorize('view', $favorite);
    return view('profile.favorite')->with('favorite', $favorite);
}

希望有幫助! 如果沒有,請添加評論!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM