Components

Basics

Description

Almost everything in MoonShine consists of components. The MoonShineComponent itself is a blade component and contains additional convenient methods for interaction in the admin panel.

Conditional Methods

You can conditionally display a component using the canSee() method.

Block::make()
->canSee(function (Block $ctx) {
return true;
})

The when() method implements a fluent interface and will execute the callback when the first argument passed to the method is true.

when($value = null, ?callable $callback = null, ?callable $default = null)
Block::make()
->when(fn() => true, fn(Block $ctx) => $ctx)

The unless() method is the opposite of the when() method.

unless($value = null, ?callable $callback = null, ?callable $default = null)

Custom View

When it's necessary to change the view using a fluent interface, you can use the customView() method.

customView(string $view, array $data = [])
Block::make('Title', [])->customView('component.my-custom-block')

On Before Render Hook

If you need to access a component immediately before rendering, you can use the onBeforeRender() method.

/**
* @param Closure(static $ctx): void $onBeforeRender
*/
public function onBeforeRender(Closure $onBeforeRender): static
Block::make('Title', [])->onBeforeRender(function(Block $ctx) {
//
})

Assets

To add assets on the fly, you can use the addAssets() method.

Block::make()
->addAssets([
new Css(Vite::asset('resources/css/block.css'))
]),

If you are implementing your own component, you can declare a set of assets in two ways.

  1. Through the assets() method:
/**
* @return list<AssetElementContract>
*/
protected function assets(): array
{
return [
Js::make('/js/custom.js'),
Css::make('/css/styles.css')
];
}
  1. Through the booted() method:
protected function booted(): void
{
parent::booted();
 
$this->getAssetManager()
->add(Css::make('/css/app.css'))
->append(Js::make('/js/app.js'));
}

Macroable Trait

All components have access to the Illuminate\Support\Traits\Macroable trait, which includes the mixin and macro methods. With this trait, you can extend the capabilities of components by adding new functionality without using inheritance.

MoonShineComponent::macro('myMethod', fn() => /*implementation*/)
 
Block::make()->myMethod()

or

// for all
MoonShineComponent::mixin(new MyNewMethods())
 
// for a specific one
Block::mixin(new MyNewMethods())

Custom Component

You can create your custom component with its own view and logic and use it in the MoonShine admin panel. To do this, use the command:

php artisan moonshine:component