https://laracasts.com/discuss/channels/laravel/how-to-apply-policy-to-a-resource-controller?page=1
How to apply policy to a resource controller?
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);
}
Awaiting for your reply, thanks in advance!
Level 50
Why can you not typehint the model? If you have a resource route with a hyphen, then the wildcard parameter will be snake_case
...
...and in the controller, you can use camelCase
for the typehinted variable name:
public function show(EmailList $emailList)
{
return view('dispatch.lists.exact')->with('list', $emailList);
}
Level 50
@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()
}
}
3
Level 50
@martinbean nice!
1
Level 1
Well, I did some changes to the code:
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;
}
....
And my route:
Route::resource('lists', 'Dispatch\EmailListsController');
What`s wrong?
Level 1
Do you register your policy in AuthServiceProvider?
Level 50
@ehsanhoushmand Did you see the last reply was four months ago?