MediumHow to Customize 403 Page with Spatie Laravel-Permission? | by Rabib Galib | Medium
Sitemap
Rabib Galib

Rabib Galib

Senior Software Engineer, Masters in Computer Science & Engineering, PHP, Python, Chatbot Expert, AI Research

How to Customize 403 Page with Spatie Laravel-Permission?

2 min readMar 19, 2023
Press enter or click to view image in full size
Customize a 403 page for spatie in laravel permission.

Spatie is an open source software used in all Laravel projects. Spatie Laravel-Permission package allows to manage user permissions & roles in a service. It provides multiple guards. Each guard will have its own set of permissions & roles that can be assigned to the guard’s users. Spatie helps to allow users access control in services.

Basically after installing this package & assigning roles with/or permissions to users, while operating any service or functionality if that part of task is not assigned to certain users then by default those users will see a laravel page view mentioning those users that they do not have any right roles/permission.

Press enter or click to view image in full size
User does not have any right roles on specific request.

Let’s presume, a functional block of controller code is defined in the route within a group where a user requires an admin role to access that service.

A GET request to avail consumers ticket details.

If the role is not assigned to that user then domain.com/consumers/1 route will render a default laravel page view by the exception handler.

Get Rabib Galib’s stories in your inbox

Join Medium for free to get updates from this writer.

Now, to customize & render a new page view for unauthorized user access, we do need to do following steps.

Step 1 (Good to know): In laravel, if we understand the request life cycle in depth. We came to know that actually in App\Exceptions\Handler class, error and exception handling is configured. This class is accountable for all exceptions thrown by the application are logged and then rendered to the user.

Here the code part 👇

Step 2 (Put custom code): Put below codebase in App\Exceptions\Handler class. And add use Spatie\Permission\Exceptions\UnauthorizedException; after namespace.

Step 3 (Design 403 page view): Now create a file names errors/403.blade.php under resources/views. Then inside the 403.blade.php write the below code.

Custom 403 page code for unauthorized users.

Now, we are good to go with new 403 page view.

Press enter or click to view image in full size
Custom 403 page view for unauthorized user access.

That’s All. Have fun 🔥 💪

If you have any query, please put in below. Find me on Github.

--

--

Rabib Galib
Rabib Galib

Written by Rabib Galib

Senior Software Engineer, Masters in Computer Science & Engineering, PHP, Python, Chatbot Expert, AI Research