Webplaats's avatar

Should policies be checked at create() and store()?

In the documentation I find examples for the action that normally would return the corresponding view. But what about the action that does the actual creating, the store() method. Must both not get the same policy checks?

Perhaps like so:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller
{

    public function create()
    {
        $this->authorize('create', 'App\Post');

        // 
    }

    public function store(Request $request)
    {
        $this->authorize('create', 'App\Post');

        // 
    }
}

This look like good practice to me, but I don't find it mentioned in the docs. Some feedback would be appreciated!

0 likes
5 replies
andreich1980's avatar

I do it. Because you shouldn't go to create page is you couldn't save it.

andreich1980's avatar

Although if a user doesn't have permissions to open create page then we assume that he couldn't send post request and reach your store method. But you better add it to the store method, because there are "bad guys" who would send the post request manually somehow.

martinbean's avatar
Level 80

@webplaats Yes. Why should you be able to view the create form if you can’t actually persist the model?

If you have a policy and you use $this->authorizeResource(Post::class) in your controller’s constructor, then Laravel will apply the create() policy method on both the create() and store() controller actions. It also means you don’t need to add $this->authorize() calls to every method if you’re using a resource controller.

2 likes
Webplaats's avatar

Thank you both @andreich1980 and @martinbean ! You confirm what I thought is good practice. And you taught me something new with $this->authorizeResource(Post::class) for in the constructor in a controller. Going to test that, good to know :-)

1 like

Please or to participate in this conversation.