通过Controller helper授权:方法authorize()不存在 - Laravel 5.5

时间:2017-12-13 07:58:11

标签: php laravel laravel-5

我定义PostPolicy.php来处理可以访问操作的人 我正在尝试处理PUT请求以更新帖子,但它似乎无法正常工作。

namespace App\Policies;

use App\Models\Users;
use App\Models\Posts;
use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    public function view(Users $user, Posts $posts)
    {
        return true;
    }

    public function create(Users $user)
    {
        return true;
    }

    public function update(Users $user, Posts $posts)
    {
        return true; //$user->id === $posts->user_id;
    }

    public function delete(Users $user, Posts $posts)
    {
        return $user->id === $posts->user_id;
    }
}

我在AuthServiceProvider.php

中注册了此政策
protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    App\Models\Posts::class => App\Policies\PostPolicy::class,
];

我的路线:

Route::put('post/update/{id}', 'CMS\PostController@update');

最后,这是我的控制器

namespace App\Http\Controllers\CMS;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Models\Posts as PostModel;
use LRedis;
use Illuminate\Http\Request;

class PostController extends BaseController
{
    public function __construct()
    {

    }

    public function update (Request $request, PostModel $postModel) {
        $this->authorize('update', $postModel);

    }

    public function subcribe () {
    }
}

当我提交表单时,我收到错误Method [authorize] does not exist on [App\Http\Controllers\CMS\PostController].

我正在按照documentation进行演示。

我的错误是什么?我错过了任何进展中吗?

4 个答案:

答案 0 :(得分:1)

您应该在项目文件的 App\Providers\AuthServiceProvider.php 文件中声明所有策略。在这种情况下,您必须像这样声明 PostPolicy:

在 AuthServiceProvider.php 中:

protected $policies = [
    // 'App\Model' => 'App\Policies\ModelPolicy',
        Post::class => PostPolicy::class,
];

可以通过查看laravel官方文档了解更多信息enter link description here

答案 1 :(得分:0)

authorize特征提供Illuminate\Foundation\Auth\Access\AuthorizesRequests方法。

您可以直接将此特性添加到控制器中,也可以让控制器扩展Laravel(App\Http\Controllers\Controller)附带的默认控制器,因为它已经具有此特征(以及{{1} }和DispatchesJobs)。

答案 2 :(得分:0)

生成的控制器扩展了默认的 Illuminate\Routing\Controller,而不是像在全新的 Laravel 安装中那样使用通常的 App\Http\Controllers\Controller

为了能够使用与授权相关的方法,您必须在类中使用 Illuminate\Foundation\Auth\Access\AuthorizesRequests 特性:

<?php
namespace Module\Posts\Http\Controllers;

// Add this use statement
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;

class PostController extends Controller
{
    use AuthorizesRequests;

    public function __construct()
    {
        $this->authorizeResource(Post::class, 'post');
    }

    // ...
}

答案 3 :(得分:0)

您可以向控制器添加 Illuminate\Foundation\Auth\Access\AuthorizesRequests 特征