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

Wireuse Laravel Package

foxws/wireuse

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require foxws/wireuse
    

    Publish config if needed (e.g., for customizations):

    php artisan vendor:publish --tag="wireuse-config"
    
  2. First Use Case: Use the HasRouteKey trait to automatically resolve model route keys (e.g., slug instead of id) in Livewire components:

    use Foxws\WireUse\Traits\HasRouteKey;
    
    class PostComponent extends Component
    {
        use HasRouteKey;
    
        public $post;
    
        public function mount(Post $post)
        {
            $this->post = $post;
        }
    
        // Automatically resolves `post->slug` instead of `post->id`
        public function render()
        {
            return view('livewire.post-component');
        }
    }
    
  3. Key Documentation:


Implementation Patterns

Core Workflows

  1. Model Route Key Resolution:

    • Replace manual id usage with HasRouteKey for cleaner URLs and API routes.
    • Example: A UserProfile component using email as the route key:
      use HasRouteKey;
      
      class UserProfile extends Component
      {
          use HasRouteKey;
      
          public $user;
      
          protected $routeKeyName = 'email'; // Override default
      }
      
  2. Property Synthesizers:

    • Dynamically generate properties from model relationships or computed values.
    • Example: Auto-synthesize a fullName property from firstName and lastName:
      use Foxws\WireUse\Traits\HasSynthesizedProperties;
      
      class UserComponent extends Component
      {
          use HasSynthesizedProperties;
      
          public $user;
      
          protected $synthesizedProperties = [
              'fullName' => fn() => "{$this->user->firstName} {$this->user->lastName}",
          ];
      }
      
  3. Component Extensions:

    • Extend Livewire components with shared logic (e.g., Page for layout management):
      use Foxws\WireUse\Components\Page;
      
      class Dashboard extends Page
      {
          // Inherits layout, title, and meta tags from `Page`
          public function render()
          {
              return view('livewire.dashboard');
          }
      }
      
  4. Form Handling:

    • Use HasForm trait for validation and submission logic:
      use Foxws\WireUse\Traits\HasForm;
      
      class ContactForm extends Component
      {
          use HasForm;
      
          protected $rules = [
              'name' => 'required|max:255',
              'email' => 'required|email',
          ];
      
          public function submit()
          {
              $this->validate();
              // Handle submission
          }
      }
      

Integration Tips

  • Blade Integration: Use wireuse directives in Blade templates for dynamic content:
    @wireuse('post', $post)
        <h1>{{ $post->title }}</h1>
    @endwireuse
    
  • API Responses: Leverage HasRouteKey to ensure API responses use route keys (e.g., slug instead of id):
    return response()->json($this->post->toArray());
    
  • Testing: Mock synthesized properties or route keys in unit tests:
    $component = new PostComponent();
    $component->setModel(new Post(['slug' => 'test-slug']));
    $this->assertEquals('test-slug', $component->getRouteKey());
    

Gotchas and Tips

Pitfalls

  1. Route Key Conflicts:

    • If a model has no defined route key (e.g., getRouteKey()), HasRouteKey will fall back to id. Explicitly set $routeKeyName to avoid ambiguity:
      protected $routeKeyName = 'slug'; // Force usage
      
  2. Synthesized Property Overrides:

    • Synthesized properties override existing ones. Use protected $synthesizedProperties carefully to avoid unintended side effects:
      // ❌ Overrides `user->name` if it exists
      protected $synthesizedProperties = ['name' => fn() => 'Default Name'];
      
      // ✅ Safe: Uses `user->name` if it exists
      protected $synthesizedProperties = ['fullName' => fn() => "{$this->user->name}"];
      
  3. Component Lifecycle:

    • Traits like HasForm assume mount() is called. If using wire:model, ensure the component is properly initialized:
      // ❌ May fail if `mount()` isn't called
      public function updatedField()
      {
          $this->validate(); // Requires `HasForm` rules
      }
      
  4. Blade Directive Scope:

    • @wireuse directives must wrap Livewire components or properties. Avoid using them outside Livewire contexts:
      @wireuse('post') <!-- ❌ Error: Not inside a Livewire component -->
          <p>{{ $post->title }}</p>
      @endwireuse
      

Debugging

  1. Route Key Issues:

    • Check php artisan route:list to verify route key usage. If a route uses id but the model uses slug, update the route definition:
      Route::get('/posts/{post:slug}', [PostController::class, 'show']);
      
  2. Synthesized Property Errors:

    • Use dd($this->synthesizedProperties) to inspect generated properties during development.
  3. Form Validation:

    • Validate rules in HasForm are correctly scoped to the component’s properties:
      protected $rules = [
          'user.name' => 'required', // ❌ May fail if `name` isn’t directly on `$this`
          'name' => 'required',      // ✅ Correct for `$this->name`
      ];
      

Extension Points

  1. Custom Traits:

    • Extend existing traits (e.g., HasRouteKey) by publishing the config and overriding defaults:
      // config/wireuse.php
      'route_key' => [
          'default' => 'uuid', // Override global default
      ];
      
  2. New Synthesizers:

    • Add custom synthesizers by extending Foxws\WireUse\Traits\HasSynthesizedProperties:
      protected $synthesizedProperties = [
          'formattedDate' => fn() => $this->date->format('Y-m-d'),
      ];
      
  3. Component Overrides:

    • Override Page or other base components to modify shared behavior:
      class CustomPage extends \Foxws\WireUse\Components\Page
      {
          public function getTitle()
          {
              return 'Custom Title: ' . parent::getTitle();
          }
      }
      
  4. Testing Utilities:

    • Use WireUse::fake() to mock synthesized properties or route keys in tests:
      WireUse::fake([
          'route_key' => 'test-slug',
          'synthesized' => ['fullName' => 'Test User'],
      ]);
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui