mycmdev / nova-modules

A Laravel Nova Tool helping modularize your application
MIT License
7 stars 6 forks source link

Putting Nova modules inside laravel-modules #8

Open binaryfire opened 2 years ago

binaryfire commented 2 years ago

Thanks for the great package! I already use nwidart/laravel-modules and would like to my Nova modules inside the existing models.

Eg. /modules/shop/nova for my e-commerce Nova files.

Is there a way of doing this?

Thanks!

Kaylakaze commented 2 years ago

It's actually pretty easy. Just add:

Nova::serving(function (ServingNova $event) {
            Nova::resources($this->resources());
            Nova::cards($this->cards());
            Nova::dashboards($this->dashboards());
            Nova::tools($this->tools());
            Nova::script(
                $this->moduleNameLower,
                module_path($this->moduleName, '/dist/js/' . $this->moduleNameLower . '.js')
            );
            Nova::style(
                $this->moduleNameLower,
                module_path($this->moduleName, '/dist/css/' . $this->moduleNameLower . '.css')
            );
        });

to the boot section of your module's service provider (make sure to add all the use statements)

Then add this method to the service provider:

protected function resources()
    {
        $directory = module_path($this->moduleName, '/Nova/Resources');
        $namespace = config('modules.namespace') . "\\" . $this->moduleName . "\\Nova";
        $resources = [];

        foreach ((new Finder)->in($directory)->files() as $resource) {
            $resource = str_replace(
                '.php',
                '',
                $namespace."\\Resources\\".Str::afterLast($resource, DIRECTORY_SEPARATOR)
            );

            if (is_subclass_of($resource, Resource::class) &&
                ! (new ReflectionClass($resource))->isAbstract() &&
                ! (is_subclass_of($resource, ActionResource::class))) {
                $resources[] = $resource;
            }
        }

        return $resources;
    }

Then put your Nova Resources in /Nova/Resources.

I'd recommend updating your module stubs if you plan to do this often. That doesn't solve potential file generation issues, but it will load your resources into Nova.