我在这里读到: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:此操作未经授权。
授权策略的执行是正确的?
我尝试dd($user)
查看方法(FavoritePolicy),结果显示正在记录用户数据。这是真的
但是我试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
}