byscripts/static-entity
Static Entity provides model/entity-like behavior backed by static arrays. Define constants and a dataset to access rich objects without a database—ideal for enums, reference lists, and small lookup tables in PHP/Laravel apps.
Installation
composer require byscripts/static-entity
Add the service provider to config/app.php:
'providers' => [
// ...
Byscripts\StaticEntity\StaticEntityServiceProvider::class,
],
Publish Config & Migrations
php artisan vendor:publish --provider="Byscripts\StaticEntity\StaticEntityServiceProvider"
Run migrations:
php artisan migrate
Define a Static Entity
Create a migration for your static entity (e.g., users_roles):
Schema::create('users_roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
Generate Model & Repository
php artisan make:model Role -m
Extend the base StaticEntity model:
namespace App\Models;
use Byscripts\StaticEntity\StaticEntity;
class Role extends StaticEntity
{
protected $table = 'users_roles';
}
First Usage
use App\Models\Role;
// Create a new role
$role = Role::create(['name' => 'Admin', 'slug' => 'admin']);
// Fetch all roles
$roles = Role::all();
// Find by slug
$adminRole = Role::findBySlug('admin');
Create/Update
Use create() or update() with name and slug:
$category = Category::create(['name' => 'Electronics', 'slug' => 'electronics']);
Bulk Operations
Use insert() for batch creation:
$data = [
['name' => 'Premium', 'slug' => 'premium'],
['name' => 'Basic', 'slug' => 'basic'],
];
Category::insert($data);
Soft Deletes Enable soft deletes in the model:
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends StaticEntity
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
Slug-Based Lookups
$category = Category::findBySlug('electronics');
$categories = Category::whereSlugLike('ele%')->get();
Ordering & Pagination
$categories = Category::orderBy('name')->paginate(10);
Eager Loading Relationships If extended with relationships:
$products = Product::with('category')->get();
Policy Authorization
// app/Policies/CategoryPolicy.php
public function update(User $user, Category $category)
{
return $user->isAdmin();
}
API Resources
// app/Http/Resources/CategoryResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'slug' => $this->slug,
];
}
Form Request Validation
// app/Http/Requests/StoreCategoryRequest.php
public function rules()
{
return [
'name' => 'required|string|max:255',
'slug' => 'required|string|unique:categories,slug',
];
}
Custom Scopes
class Category extends StaticEntity
{
public function scopeActive($query)
{
return $query->where('is_active', true);
}
}
Observers
// app/Observers/CategoryObserver.php
public function saving(Category $category)
{
if (empty($category->slug)) {
$category->slug = Str::slug($category->name);
}
}
Events
// app/Listeners/LogCategoryCreated.php
public function handle(CategoryCreated $event)
{
Log::info("Category created: {$event->category->name}");
}
Slug Uniqueness
Ensure slug is unique in migrations. The package does not auto-generate slugs—handle this in observers or requests.
Missing findBySlug Method
The base StaticEntity model lacks findBySlug(). Override it:
public function findBySlug($slug)
{
return static::where('slug', $slug)->first();
}
Case Sensitivity in Slugs
If using whereSlugLike(), ensure database collation supports case-insensitive searches (e.g., utf8mb4_unicode_ci).
Mass Assignment Risks
Explicitly define $fillable in your model to avoid mass assignment vulnerabilities:
protected $fillable = ['name', 'slug'];
Check for Missing Config
Verify config/static_entity.php exists after publishing. Defaults may not work if missing.
Migration Issues If migrations fail, check for:
id already exists).slug column in the table.Observer Conflicts If observers aren’t triggering, ensure:
AppServiceProvider@boot().Index the slug Column
Add an index in migrations for faster lookups:
$table->string('slug')->unique();
$table->index('slug');
Cache Frequent Queries Use Laravel’s cache for static entities that rarely change:
$roles = Cache::remember('all_roles', now()->addHours(1), function () {
return Role::all();
});
Custom Validation
Override validateUniqueSlug in the model for custom slug rules:
protected function validateUniqueSlug($slug)
{
return static::where('slug', $slug)
->where('id', '!=', $this->id)
->doesntExist();
}
API Versioning Use Laravel’s API resources to version responses without changing the database:
// v1
public function toArray($request) { ... }
// v2
public function toArray($request) { ... }
Localization Support Store translated names in JSON and add accessors:
protected $casts = ['translations' => 'array'];
public function getNameAttribute()
{
return $this->translations['en'] ?? $this->name;
}
How can I help you explore Laravel packages today?