php-无法在Laravel 5.3中运行策略

我一直在关注Laravel授权文档,试图通过使用策略来构建“是否允许用户这样做”功能,但我无法使其正常工作.我不断收到此操作是未经授权的,我也尝试过使用路由中间件.

PagePolicy.php:

namespace App\Policies;

use App\Models\User;
use App\Models\Page;

use Illuminate\Auth\Access\HandlesAuthorization;

class PagePolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the page.
     *
     * @param  App\Models\User  $user
     * @param  App\Models\Page  $page
     * @return mixed
     */
    public function view(User $user, Page $page)
    {
        return $user->id === $page->user_id;
    }

    /**
     * Determine whether the user can create pages.
     *
     * @param  App\Models\User  $user
     * @return mixed
     */
    public function create(User $user)
    {

    }

    /**
     * Determine whether the user can update the page.
     *
     * @param  App\Models\User  $user
     * @param  App\Models\Page  $page
     * @return mixed
     */
    public function update(User $user, Page $page)
    {
        //
    }

    /**
     * Determine whether the user can delete the page.
     *
     * @param  App\Models\User  $user
     * @param  App\Models\Page  $page
     * @return mixed
     */
    public function delete(User $user, Page $page)
    {
        //
    }
}

PageController.php:

namespace App\Http\Controllers;

use Auth;
use Carbon\Carbon;

use App\Models\Page;

use App\Http\Requests\PageRequest;

class PageController extends ApiController
{
    public function createNewPage(PageRequest $request)
    {
        $this->authorize('create', Page::class);

        $request->merge([
            'user_id' => Auth::id(),
            'published_at' => Carbon::now(),
        ]);

        if (Page::create($request->all())) {
            return response()->json('success', 201);
        }

        return response()->json('error', 500);
    }

}

AuthServiceProvidor.php:

namespace App\Providers;

use App\Models\Page;
use App\Policies\PagePolicy;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Page::class => PagePolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

解决方法:

我设法弄清楚了.我没有使用路由模型绑定.因此,我在页面调用之后添加了authorize(),并使用$page变量而不是Page :: class.

public function update(PageUpdateRequest $request, $pageSlug)
{
    $page = Page::where(['user_id' => Auth::id(), 'slug' => $pageSlug])->first();
    $this->authorize('update', $page);
    $page->update($request->all());
    return fractal()->item($page, new PageTransformer())->toArray();
}
上一篇:JavaScript-Soundcloud API /解决方法404错误


下一篇:php-Laravel 5 Entrust-用户属于许多应用程序