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-
ProjectsController.php
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);
//abort_unless();
$this->authorize('view',$project);
return view('project.show',compact('project'));
}
ProjectPolicy.php
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.
ProjectsController.php
public function show(Project $project, Twitter $twitter)//edited
{
$this->authorize('view',$project);//the authorization is enabled just by this loc.
return view('project.show',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.
You need to register your policy to fit your model, more informations :
https://laravel.com/docs/5.8/authorization#registering-policies
In your app/Providers/AuthServiceProvider.php
file, just add :
protected $policies = [
Project::class => ProjectPolicy::class,
];