Tricks

Resources, pages, widgets in Laravel Modules

Mar 15, 2023
jgmuchiri
Integration

About

This service provider will scan Filament directory of your activated modules (nwidart/laravel-modules) for pages, resources and widgets, and register them in filament config.

You can modify the file if your modules are in a directory other than Modules.

Installation

  1. Install json-machine package composer require halaxa/json-machine
  2. Create ModuleFilamentServiceProvider.php to your App/Providers directory
<?php
 
namespace App\Providers;
 
use Filament\PluginServiceProvider;
use Spatie\LaravelPackageTools\Package;
 
class ModuleFilamentServiceProvider extends PluginServiceProvider
{
public static string $name = 'files';
 
private $modules = [];
 
public function __construct($app)
{
parent::__construct($app);
 
$this->loadModules();
 
$this->registerFilament('pages');
$this->registerFilament('resources');
$this->registerFilament('widgets');
}
 
public function configurePackage(Package $package): void
{
parent::configurePackage($package);
}
 
public function registerFilament($type){
foreach($this->modules as $module){
 
$path = 'Modules\\'.$module.'\Filament\\'.ucfirst($type).'\\';
 
$dir = base_path('Modules/'.$module.'/Filament/'.ucfirst($type));
 
if(is_dir($dir)){
 
$files = scandir($dir);
 
foreach($files as $file)
{
if(pathinfo($file, PATHINFO_EXTENSION) !=='php') {
continue;
}
 
$class = $path.basename($file,'.php');
config()->push('filament.'.strtolower($type).'.register',$class);
}
}
}
}
 
public function loadModules(){
$module_statuses = \JsonMachine\Items::fromFile(config('modules.activators.file.statuses-file'));
foreach ($module_statuses as $name => $active) {
if (!$active) {
continue;
}
$this->modules[] = $name;
}
}
}
  1. Add \App\Providers\ModuleFilamentServiceProvider::class to config/app.php providers
  2. Move filament resources, pages, widgets from app/Filament to their respective modules. For example, Modules/<Module Name>/Filament/Pages

Your filamentphp components should now be registered.

No comments yet…