【发布时间】:2017-03-04 17:10:59
【问题描述】:
我在这里读到:https://laravel.com/docs/5.3/authorization#writing-policies
我试着喜欢这个
My 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:此操作是 未经授权。
Authorization Policies 的实现方式是正确的?
我在视图方法(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
}
【问题讨论】:
-
dd($favorite)的输出究竟是什么? -
请考虑将 dd() 的输出添加到您的问题中,因为您的评论很难阅读。
标签: php laravel authorization laravel-5.3 policies