Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Static Entity Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require byscripts/static-entity
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Byscripts\StaticEntity\StaticEntityServiceProvider::class,
    ],
    
  2. Publish Config & Migrations

    php artisan vendor:publish --provider="Byscripts\StaticEntity\StaticEntityServiceProvider"
    

    Run migrations:

    php artisan migrate
    
  3. 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();
    });
    
  4. 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';
    }
    
  5. 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');
    

Implementation Patterns

1. CRUD Workflows

  • 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'];
    }
    

2. Querying & Filtering

  • 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();
    

3. Integration with Laravel Features

  • 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',
        ];
    }
    

4. Extending Functionality

  • 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}");
    }
    

Gotchas and Tips

1. Common Pitfalls

  • 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'];
    

2. Debugging Tips

  • 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:

    • Duplicate column names (e.g., id already exists).
    • Missing slug column in the table.
  • Observer Conflicts If observers aren’t triggering, ensure:

    • The observer is registered in AppServiceProvider@boot().
    • The model uses the correct namespace.

3. Performance Optimizations

  • 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();
    });
    

4. Extension Points

  • 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;
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity