2019-06-10 12:35
浏览 287

Laravel 5.8 - 授权无需在AuthServicerProvider.php中注册ProjectPolicy即可运行

I am following Jeffrey Way's laracasts from scratch and he mentions registering the ProjectPolicy.php in AuthServiceProvider.php. However, I tried refreshing my auth page to check on some other account without doing so, and it still works.

This is a weird question because I think I'm wasting time on something which works and I shouldnt be worried about. Below is the code snippet.

Ive tried commenting quite a few LoCs which I thought could be used by the framework to authorize the pages-


public function __construct(){

      // $this->middleware('auth'); 


unedited version for the question, here.
show() method in ProjectsController.php

  public function show(Project $project, Twitter $twitter)
        // $twitter = app('twitter');
        // dd($twitter);

        // abort_if($project->owner_id !== auth()->id(),403);

        return view('',compact('project'));


    public function view(User $user, Project $project)
         return $project->owner_id == $user->id;//works even if I remove this
    }// works even if I remove the complete method.


public function show(Project $project, Twitter $twitter)//edited
        $this->authorize('view',$project);//the authorization is enabled just by this loc.

        return view('',compact('project'));

I am so confused so as to how this is still working.

How is the framework picking up authorize('view',$project); even when Im removing the view() method?

Edit: Found this on the documentations page.

Instead of manually registering model policies, Laravel can auto-discover policies as long as the model and policy follow standard Laravel naming conventions. Specifically, the policies must be in a Policies directory below the directory that contains the models. So, for example, the models may be placed in the app directory while the policies may be placed in the app/Policies directory. In addition, the policy name must match the model name and have a Policy suffix. So, a User model would correspond to a UserPolicy class.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongliang9682
    dongliang9682 2019-06-10 12:43

    You need to register your policy to fit your model, more informations :

    In your app/Providers/AuthServiceProvider.php file, just add :

    protected $policies = [
        Project::class => ProjectPolicy::class,
    点赞 评论