Hello. I have a basic resource controller and placing $this->authorize in every method isn't very good I think(maybe I am wrong). Also I have some custom methods(upload, develop) and I'd like to apply policy to those too. I found this method: $this->authorizeResource, but it always shows me "This action is unauthorized.". My model name is snake-cased(EmailList). Also my resource controller methods doesn't require model instance. Here is what I mean:
public function show($id) //--- As you see, no model instance here
{
$list = EmailList::find($id);
//$this->authorize('view', $list); //--- This works perfectly, by the way..
return view('dispatch.lists.exact')->with('list', $list);
}
@Void If you’re extending the base controller in Laravel, then you can use the authorizeResource() method:
class ArticleController extends Controller
{
public function __construct()
{
$this->authorizeResource(Article::class);
}
public function index()
{
//
}
public function create()
{
// Will call ArticlePolicy::create()
}
public function store()
{
// Will call ArticlePolicy::create()
}
public function show()
{
// Will call ArticlePolicy::view()
}
public function edit()
{
// Will call ArticlePolicy::update()
}
public function create()
{
// Will call ArticlePolicy::update()
}
public function create()
{
// Will call ArticlePolicy::delete()
}
}
class EmailListsController extends Controller
{
public function __construct()
{
$this->authorizeResource(EmailList::class);
}
....
public function show(EmailList $list)
{
return view('dispatch.lists.exact')->with('list', $list);
}
....
}
But it always returns "This action is unauthorized.". Here is my view method in EmailListPolicy file:
....
public function view(User $user, EmailList $list)
{
return $user->id === $list->user_id;
}
....