javoscript/laravel-macroable-models
Adds Macroable support to Eloquent models, letting you define and register reusable model macros for dynamic methods at runtime. Great for extending models cleanly across packages and projects without touching the model class directly.
User::hasActiveSubscription()).Model::shouldReceive('macro')->andReturn()).app()->bind())?getFooAttribute), and traits? Training may be needed.getMockBuilder()->setMethods() or custom test helpers.)README.md per model)?app() bindings, traits, or policy methods) considered and rejected?phpstorm.meta.php).User::isAdmin() if it’s used across 10+ controllers.Tag, Role) to validate the approach.// app/Models/User.php
User::macro('isAdmin', function () {
return $this->role === 'admin';
});
@deprecated comments during transition.MACROS.md file to the repo detailing all macros, their purpose, and usage examples.spatie/laravel-activitylog).composer require javoscript/laravel-macroable-models).assertTrue($user->isAdmin())).MethodNotFoundException).isActive()).User with 20+ macros).debug_print_backtrace() or Xdebug to trace execution.User::macro('isAdmin', function () {
\Log::debug('isAdmin() called for user ID: ' . $this->id);
return $this->role === 'admin';
});
getRecentOrders() could cache results if needed.| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Macro name typo | Runtime MethodNotFoundException |
IDE autocompletion, CI linting. |
| Macro logic error | Silent data corruption | Unit tests, feature flags for new macros. |
| Overuse of macros | Model bloat, reduced readability | Enforce limits (e.g., <10 macros/model). |
| Package abandonment | Unmaintained macros break | Fork or pin version in composer.json. |
| PHP version incompatibility | Macros fail to register | Test on target PHP version early. |
public function test_user_macros()
{
$user = User::factory()->admin()->create();
$this->assertTrue($user->isAdmin());
}
How can I help you explore Laravel packages today?