Get expert guidance in a few days with a Laravel code review

Laravel Model Status

Laravel Model Status stats

Downloads
3
Stars
8
Open Issues
0
Forks
0

View on GitHub →

A Laravel package to automate adding configurable status columns to models and migrations, and enforce user activity through middleware.

Laravel Model Status

A Laravel package to automate adding configurable status columns to models and migrations. This package provides an easy-to-use HasActiveScope trait, a Status enum, middleware for ensuring active users, and a custom Artisan command to streamline your workflow.


Features

  • Add a configurable status column to models and migrations.
  • Automatically handle global scopes for active statuses.
  • Enforce user activity with the EnsureAuthenticatedUserIsActive middleware.
  • Activate or deactivate models with simple methods.
  • Support dynamic configuration for column name, default value, and length.
  • Includes a make:model-status command.

Installation

You can install the package via Composer:

composer require thefeqy/laravel-model-status

Optionally, you can publish the configuration file:

php artisan vendor:publish --tag=config

Usage

Using the Trait

To use the HasActiveScope trait, include it in your model:

use Thefeqy\ModelStatus\Traits\HasActiveScope;
 
class ExampleModel extends Model
{
use HasActiveScope;
 
protected $fillable = ['name'];
}

Creating Models with status

You can use the custom Artisan command to create models and migrations with a status column automatically:

php artisan make:model-status Example

This will:

  • Create a model named Example and automatically use HaveActiveScope.
  • Add a status column to the generated migration file with the configuration values.

Querying Models

Retrieve Active Models (Default Behavior)

$activeModels = ExampleModel::all();

Include Inactive Models

$allModels = ExampleModel::withoutActive()->get();

Middleware Usage

The package includes the EnsureAuthenticatedUserIsActive middleware, which enforces that only users with an active status can access certain routes.

Add Middleware to Routes

Instead of registering a string alias for the middleware, you can reference it by class name in your route definition:

use Illuminate\Support\Facades\Route;
use Thefeqy\ModelStatus\Middleware\EnsureAuthenticatedUserIsActive;
 
Route::middleware(['auth', EnsureAuthenticatedUserIsActive::class])->group(function () {
Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
});
});
 
Route::get('/login', function () {
return 'Login page';
})->name('login');

Behavior

  • If the authenticated user's status is not active:
    • The user will be logged out.
    • A 403 Forbidden response will be returned with the message:
This account is suspended. Please contact the administrator.

Example Workflow

1- Use the make:model-status command to create a model with a status column and include the HasActiveScope trait:

php artisan make:model-status Company

2- Update the database schema to include a status column in the companies table (if not already present):

php artisan migrate
  1. Protect your routes using the middleware to ensure only active users can access them:
use App\Models\Company;
use Thefeqy\ModelStatus\Middleware\EnsureAuthenticatedUserIsActive;
 
Route::middleware(['auth', EnsureAuthenticatedUserIsActive::class])->group(function () {
Route::get('/companies', function () {
return view('companies', ['companies' => Company::get()]);
});
});
  1. Test the functionality:
  • try to access the companies route to make sure that only active companies are included in the response

Activating and Deactivating Models

The HasActiveScope trait provides two methods: activate and deactivate. These methods dynamically use the configuration values for the status column to update the mode status.

Activate a Model

$model = ExampleModel::find(1);
if ($model->activate()) {
echo "Model activated successfully!";
} else {
echo "Failed to activate model.";
}

Deactivate a Model

$model = ExampleModel::find(1);
if ($model->deactivate()) {
echo "Model deactivated successfully!";
} else {
echo "Failed to deactivate model.";
}

Configuration

Edit the config/model-status.php file to customize the column name, default value, inactive value, and length:

return [
'column_name' => 'status', // The name of the status column
'default_value' => 'active', // The value for the "active" state
'inactive_value' => 'inactive', // The value for the "inactive" state
'column_length' => 10, // The maximum length of the status column
];

If you want to use a different column name (e.g., account_status), update the column_name value in config/model-status.php and ensure the corresponding database schema matches.

Example Configuration Use Case

  • If you change the column_name to state in the config, the migration will automatically generate:
$table->string('state', 10)->default('active');
  • The global scope and the HasActiveScope trait will also dynamically adapt to use state instead of status.

Contributing

Contributions are welcome! https://github.com/thefeqy/laravel-model-status Please follow these steps:

  1. Fork the repository.
  2. Create a new branch:
    git checkout -b feature/your-feature
  3. Commit your changes:
    git commit -m "Add your feature"
  4. Push to the branch:
    git push origin feature/your-feature
  5. Open a pull request.

License

The MIT License (MIT). Please see License File for more information.

thefeqy photo

It's Muhammed ElFeqy from egypt, Software Engineer @ConvertedIn

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Thefeqy Laravel Model Status Related Articles

A Package to Manage Model Status in Laravel image

A Package to Manage Model Status in Laravel

Read article
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Securing Laravel logo

Securing Laravel

The essential security resource for Laravel devs, covering everything you need to keep your apps secure. Sign up to receive weekly security tips and monthly in depth articles, diving deep into security concepts you need to know!

Securing Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum