Certainly! With Livewire 4 (especially with Laravel 12’s improved package discovery), you have several streamlined options for loading components from your package. Here’s how you can approach it:
1. Automatic Discovery of Package Components
Livewire now supports automatic component discovery, but out of the box, it only scans your main resources/views/livewire and app/Livewire directories. For package development, you’ll still need to let Livewire know where your package components live.
If Using Class-based Components
If your Livewire components are PHP classes (not single-file components), you can bulk-register a namespace in your package's PackageServiceProvider:
use Livewire\Livewire;
public function boot()
{
Livewire::componentNamespace('Packages\\myPackage\\Livewire', __DIR__.'/../Livewire');
}
This tells Livewire to automatically discover components in that namespace. Adjust the namespace and path as needed for your package.
For Single-file Components (SFC)
If you want to support single-file components in your package (i.e., .blade.php file with a PHP class in the same file), you’ll need to tell Livewire where to scan.
You can do this in your package’s boot method:
use Livewire\Livewire;
public function boot()
{
Livewire::componentDirectory(__DIR__.'/../resources/views/components');
}
Or for even more structure, consider:
Livewire::componentSource('my-package', __DIR__.'/../resources/views/components');
Now, in your Blade, you can reference the components like:
<livewire:my-package::your-component-name />
2. Publishing/Loading Views
If your components rely on views in your package, make sure you register the view path as well:
public function boot()
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'my-package');
}
Then, in your Livewire component, use the named view:
return view('my-package::components.your-component');
3. Summary of Steps
- For class-based components: use
Livewire::componentNamespace to autoload all components from that namespace.
- For single-file components: use
Livewire::componentDirectory or Livewire::componentSource.
- Always register your view paths with
loadViewsFrom in your package service provider.
Example: PackageServiceProvider Registration
use Livewire\Livewire;
public function boot()
{
// For class-based components
Livewire::componentNamespace('Packages\\myPackage\\Livewire', __DIR__.'/../Livewire');
// For SFCs
Livewire::componentDirectory(__DIR__.'/../resources/views/components');
// Register views
$this->loadViewsFrom(__DIR__.'/../resources/views', 'my-package');
}
Reference:
If you want truly dynamic loading/discovery (for example, based on config or filesystem structure), you’d need to scan the directory yourself and register using Livewire::component() in a loop.
Let me know if you have a specific use-case or structure and I can tailor the example!