scheMeZa
8 months ago

Using model event to constraint CRUD actions

Posted 8 months ago by scheMeZa

Hello everyone,

Sorry for the length of this question, but it's really just to be thorough.

I’m creating an app with roles and permissions associated to each `Us;

An administrator is a User with the administrator role assigned to it.

So business logic says that only administrators are allowed to create, update, or delete Posts.

Usually I would make sure the user is logged in, and is an administrator in its controller such as [email protected].

But, I’ve started using a new approach to these kinds of constraints, and want to know what your opinion is.

Let’s say I want to lockdown a `Pos `crea method: In `App\Post.p:

class Post extends Model {
    protected $dispatchesEvents = [
        ‘creating’ => PostCreating::class,
    ];
}

In EventServiceProvider.php:

class EventServiceProvicer {

    protected $listen = [
        PostCreating::class => [
            EnsureAdministratorLoggedIn::class,
        ],
    ];

}

In App\Events\PostCreating.php:

class PostCreating {
    // No need to do anything here, just used in EventServiceProvider
}

In App\Listeners\EnsureAdministratorLoggedIn.php:

public function handle($event) {
    if (
        !Auth::check() ||
        !Auth::user()->hasRole('administrator')
    ) {
        throw new \Exception(get_class($event) . ": Only administrators may do this action.");
    }
}

Is this approach wrong? Do you have a better approach?

I've noticed that implementing tests are harder now, I cannot use a PostFactory out of the box, I need to make sure an administrator is logged in for the model to create.

Please sign in or create an account to participate in this conversation.