是否可以将Laravel策略同时应用于路由和自定义功能?

时间:2019-03-06 12:19:24

标签: laravel policy

我要使用相同的策略,因此我有位置策略和一个api以及一个自定义助手,

这里是示例:

1。路由/ API读取位置记录:

this._commands.length * this._commands.length

2。自定义功能/助手以读取位置记录

  

LocationHelper.php

 Route::group(['middleware' => 'policy:view,location'], function () {
        // Read location
        Route::post('/locations/{location_id}', [
            'uses'       => 'LocationApiController@read'
        ]);
  });

问题是:

虽然调用位置读取路由/ api策略将适用,而从/** * Class LocationHelper. */ class LocationHelper { /** @var LocationRepositoryInterface */ private $locationRepo; /** * ReminderHelper constructor. */ public function __construct() { $this->locationRepo = App::make(LocationRepositoryInterface::class); } /** * @param int $locationId */ public function readLocation($locationId) { $this->locationRepo->read($locationId); } } 调用读取功能则将不适用

我想要的是对两者都应用相同的政策。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以在检索用户之后手动调用该策略。例如:

$allowed = Auth::user()->can('view', Location::firstOrFail($locationId));

如果不允许用户查看资源,则返回403,如下所示:

abort_unless($allowed, 403);