Implementing User Suspension in Your Laravel Application
This guide will walk through implementing user suspension in a Laravel application. This functionality allows you to temporarily or permanently suspend users and notify them accordingly.
Step 1: Add Suspension Columns to the Users Table
First, we need to update our users
table to include columns for tracking suspension status and reason.
- Create a new migration:
- In the migration file, add the following code:
- Run the migration
Step 2: Update the User Model
- Open
app/Models/User.php
file. - Use the
Suspendable
trait and add the necessary attribute casts:
Laravel 11 and newer versions utilize casts
methods for property casting:
Step 3: Create the Suspendable Trait
- Create a new PHP file at
app/Traits/Suspendable.php
- Add the following code to that file:
This trait adds the suspend
and unsuspend
methods to the User
model for suspending and unsuspending accounts easily. This also provides the is_banned
and is_suspended
attributes for checking suspension status.
Step 4: Create Notifications
- Create notification classes:
- Edit
app/Notifications/UserSuspendedNotification.php
- Edit
app/Notifications/UserUnsuspendedNotification.php
We are almost done 😀 Let’s take a look at the usage example:
Now, The only thing that remains is to check whether the authenticated user is suspended and restrict their access to the application. Let’s do this in the next step.
Step 5: Restrict Application Access for Suspended Users
- Create Middleware
- In the middleware file
app/Http/Middleware/CheckUserSuspension.php
, add the following logic to handle restricted access for suspended users:
- Apply Middleware to Routes:
In routes/web.php
or routes/api.php
apply the middleware to the routes you want to protect:
Otherwise, you can add this middleware to the web
or api
middleware group to apply it to a set of routes.
Step 6: Applying to Middleware Groups (optional)
- Laravel 11 or newer
- For Laravel 10 or older
Conclusion
By following this guide, you have successfully implemented user suspension functionality in your Laravel application. This approach keeps your User
model clean and encapsulates the suspension logic within a reusable Suspendable
trait.
This feature allows you to manage user access effectively by suspending and unsuspending users as needed. This not only enhances the security and control over user activities but also ensures a better user management system.
Happy coding! ❤️