New in v6: Granular User Access, using Custom Closures

When it comes to building complex applications, controlling access to certain features or actions is paramount. Starting with Backpack...

Karan Datwani
Karan Datwani
Share:

When it comes to building complex applications, controlling access to certain features or actions is paramount. Starting with Backpack 6.2.4, you can control user access on a per-entry and per-operation basis.

How? By using the new setAccessCondition() 🎉

Get Specific with User Access

Even before this version, you could handle user access to certain operations:

$this->crud->allowAccess('operation_name');
$this->crud->allowAccess(['list', 'update', 'delete']);
$this->crud->denyAccess('operation');
$this->crud->denyAccess(['update', 'create', 'delete']);

But now... you have even more granular control, using "access closures".

Example 1 - For Existing Operations

Let's consider a scenario where we have an edit button, which should only be visible if created by the user. You can now easily show/hide that button, depending on a condition:

$this->crud->setAccessCondition('update', function ($entry) {
    return $entry->user_id == backpack_user()->id ? true : false;
});

Notice that we don't just hide the button... we set the access for the update operation. This means we don't only hide the button... but also prevent the update actions from working. All in one go 🤯

Example 2 - For Custom Operations

Suppose you want to add an 'Approve' button to your CRUD operations, but not all entries should be allowed for approval.

// approve.blade.php
@if ($crud->hasAccess('approve', $entry))
  <a href="{{ url($crud->route.'/'.$entry->getKey().'/approve') }} " class="btn btn-xs btn-default"><i class="la la-thumbs-up"></i> Approve</a>
@endif

Then in your CrudController, define access condition using the setAccessCondition method:

$this->crud->setAccessCondition('approve', function ($entry) {
    return $entry->category == 1 ? true : false;
});

Of course, you can also restrict access based on user permissions:

$this->crud->setAccessCondition('approve', function ($entry) {
    return backpack_user()->isSuperAdmin() ? true : false;
});

Conclusion

With custom access closures in Backpack, you can easily control user access, based on your defined conditions.

To explore further details and implementation, check out the following resources:

Want to receive more articles like this?

Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.

Reactions & Comments

What do you think about this?

Latest Articles

Wondering what our community has been up to?