### Complete Project Setup and Installation
Source: https://github.com/moonshine-software/doc/blob/4.x/en/contribution.md
Finalize the development setup by creating the .env file, generating the application key, linking storage, migrating the database, creating a MoonShine user, and starting the development server.
```shell
php artisan key:generate
php artisan storage:link
php artisan migrate --seed
php artisan moonshine:user
php artisan serve
```
--------------------------------
### Example Config File Structure
Source: https://github.com/moonshine-software/doc/blob/4.x/en/recipes/change-config.md
This is an example of the generated configuration file structure.
```php
return [
'var' => 'foo',
'bar' => 'test',
];
```
--------------------------------
### Full MoonShine Configuration Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/configuration.md
This is an example of the complete `moonshine.php` configuration file, showing all available settings.
```php
return [
'title' => env('MOONSHINE_TITLE', 'MoonShine'),
'logo' => '/assets/logo.png',
'logo_small' => '/assets/logo-small.svg',
'use_migrations' => true,
'use_notifications' => true,
'use_database_notifications' => true,
'use_profile' => true,
'use_routes' => true,
'domain' => env('MOONSHINE_DOMAIN'),
'prefix' => 'admin',
'middleware' => [
// ...
],
'auth' => [
'enabled' => true,
'guard' => 'moonshine',
'middleware' => [
Authenticate::class,
],
// ...
],
'layout' => \MoonShine\Laravel\Layouts\AppLayout::class,
'palette' => \MoonShine\ColorManager\Palettes\PurplePalette::class,
'locale' => 'en',
'locales' => ['en', 'ru'],
// ...
];
```
--------------------------------
### Install Laravel with MoonShine Starter Kit
Source: https://github.com/moonshine-software/doc/blob/4.x/en/quick-start.md
Installs a new Laravel application pre-configured with MoonShine using the starter kit.
```shell
laravel new example-app --using=moonshine/app
```
--------------------------------
### Configure MoonShine Installation
Source: https://github.com/moonshine-software/doc/blob/4.x/en/quick-start.md
Runs the MoonShine installation command with the quiet flag to set up the admin panel and create the first administrator.
```shell
php artisan moonshine:install -Q
```
--------------------------------
### CardsBuilder Thumbnail Configuration Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Example of configuring the card thumbnail using the `thumbnail()` method with a column name.
```php
CardsBuilder::make(
items: Article::paginate()
)
->fields([Text::make('Text')])
->thumbnail('thumbnail')
// or by url
// ->thumbnail(fn() => 'https://example.com/image.png')
```
--------------------------------
### Install Laravel Installer
Source: https://github.com/moonshine-software/doc/blob/4.x/en/quick-start.md
Installs the Laravel installer globally. Ensure you have Composer installed.
```shell
composer global require laravel/installer
```
--------------------------------
### Install MoonShine Scout Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/search.md
Install the `moonshine/scout` package using Composer and publish its configuration file.
```shell
composer require moonshine/scout
```
```shell
php artisan vendor:publish --provider="MoonShine\Scout\Providers\ScoutServiceProvider"
```
--------------------------------
### Install ApexCharts Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/metrics.md
To enable line and donut chart metrics, install the `moonshine/apexcharts` package using Composer.
```shell
composer require moonshine/apexcharts
```
--------------------------------
### CardsBuilder Title Configuration Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Example of configuring the card title using the `title()` method.
```php
CardsBuilder::make(
fields: [Text::make('Text')],
items: Article::paginate()
)
->title('title')
```
--------------------------------
### Create Img Component Instance
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/img.md
Instantiate the Img component with a source path. This is the basic setup for displaying an image.
```php
make(?string $src)
```
```php
Img::make('path_to_file);
```
```blade
```
--------------------------------
### CardsBuilder Subtitle Configuration Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Example of configuring the card subtitle using the `subtitle()` method.
```php
CardsBuilder::make(
items: Article::paginate()
)
->fields([Text::make('Text')])
->title('title')
->subtitle(static fn() => 'Subtitle')
```
--------------------------------
### Example Post Policy
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/authorization.md
Define authorization logic for a Post resource by implementing methods like `viewAny`, `view`, `create`, `update`, `delete`, etc. This example allows all actions.
```php
namespace App\Policies;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
use MoonShine\Laravel\Models\MoonshineUser;
class PostPolicy
{
use HandlesAuthorization;
public function viewAny(MoonshineUser $user)
{
return true;
}
public function view(MoonshineUser $user, Post $model)
{
return true;
}
public function create(MoonshineUser $user)
{
return true;
}
public function update(MoonshineUser $user, Post $model)
{
return true;
}
public function delete(MoonshineUser $user, Post $model)
{
return true;
}
public function restore(MoonshineUser $user, Post $model)
{
return true;
}
public function forceDelete(MoonshineUser $user, Post $model)
{
return true;
}
public function massDelete(MoonshineUser $user)
{
return true;
}
}
```
--------------------------------
### Clone Demo Project
Source: https://github.com/moonshine-software/doc/blob/4.x/en/contribution.md
Clone the demo project to start development. This is the first step in setting up your local development environment.
```shell
git clone git@github.com:moonshine-software/demo-project.git .
```
--------------------------------
### Usage Example of Include Shortcode
Source: https://github.com/moonshine-software/doc/blob/4.x/README.md
This example demonstrates how to use the 'include' shortcode in a markdown file to render another markdown file with parameters.
```markdown
@include('_includes/test', 'test', 3)
```
--------------------------------
### Optimized MoonShine Configuration
Source: https://github.com/moonshine-software/doc/blob/4.x/en/configuration.md
This example shows a partial configuration for `moonshine.php`, including only settings that differ from default values for cleaner management.
```php
return [
'title' => 'My MoonShine Application',
'use_migrations' => true,
'use_notifications' => true,
'use_database_notifications' => true,
];
```
--------------------------------
### Install MoonShine Two-Factor Authentication
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authentication.md
Install the Two-Factor Authentication package for MoonShine using Composer.
```shell
composer require moonshine/two-factor
```
--------------------------------
### Grid and Column Example (PHP)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/grid.md
Demonstrates creating a grid with two columns using the PHP syntax. Each column spans 6 units on all screen sizes.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:3]
use MoonShine\UI\Components\Layout\Column;
use MoonShine\UI\Components\Layout\Grid;
use MoonShine\UI\Fields\Text;
Grid::make([
Column::make(
[
Text::make('Text')
],
colSpan: 6,
adaptiveColSpan: 6
),
Column::make(
[
Text::make('Text')
],
colSpan: 6,
adaptiveColSpan: 6
),
])
```
--------------------------------
### Install Import/Export Dependency
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/import-export.md
Install the necessary composer package for import and export functionality.
```shell
composer require moonshine/import-export
```
--------------------------------
### Basic CardsBuilder Usage Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Illustrates the fundamental usage of CardsBuilder by providing sample items and fields.
```php
CardsBuilder::make(
[
['id' => 1, 'title' => 'Title 1'],
['id' => 2, 'title' => 'Title 2'],
],
[
ID::make(),
Text::make('title')
]
)
```
--------------------------------
### Example: Table with FormBuilder Filters and Async Loading
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/table-builder.md
Demonstrates setting up a `FormBuilder` for filters and a `TableBuilder` that loads data asynchronously, linked by form and table names.
```php
FormBuilder::make()
->name('dashboard-form')
->fields([
Date::make('Date')
])
->dispatchEvent([
AlpineJs::event(
JsEvent::TABLE_UPDATED, 'dashboard-table'
)
]),
TableBuilder::make()
->name('dashboard-table')
->withFilters('dashboard-form')
->async()
->fields([
Text::make('Title')->sortable()
])
->items([
['title' => fake()->word()]
])
```
--------------------------------
### Outline Icon Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/icons.md
Renders an icon from the Outline set. This is the default behavior if no prefix is specified.
```php
->icon('academic-cap')
```
--------------------------------
### Install MoonShine Panel
Source: https://github.com/moonshine-software/doc/blob/4.x/en/installation.md
Run this Artisan command to set up the MoonShine admin panel in your project. This command initiates the configuration process.
```shell
php artisan moonshine:install
```
--------------------------------
### Run Migrations for Socialite
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authentication.md
Run database migrations after installing the Socialite package.
```shell
php artisan migrate
```
--------------------------------
### Markdown Partial Example Content
Source: https://github.com/moonshine-software/doc/blob/4.x/README.md
This is an example of the content for a markdown partial file that can be included using the 'include' shortcode.
```markdown
## Hello world
%s - %s
```
--------------------------------
### AsyncMethod Attribute Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-button.md
Illustrates how to mark methods with the `AsyncMethod` attribute to make them callable via `ActionButton`. Includes examples for notifications, redirects, and custom JSON responses.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:1]
use MoonShine\Support\Attributes\AsyncMethod;
// With notification
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
return $response->toast('My message', ToastType::SUCCESS);
}
// Redirect
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
return $response->redirect('/');
}
// Redirect
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): RedirectResponse
{
return back();
}
// Exception
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): void
{
throw new \Exception('My message');
}
// Custom JSON response
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request)
{
return JsonResponse::make()->html('Content');
}
```
--------------------------------
### Install MoonShine Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/contribution.md
Add the MoonShine package to your project's packages directory and install its dependencies. This step is crucial for local development.
```shell
cd packages && git clone git@github.com:moonshine-software/moonshine.git && cd moonshine && composer install && npm install
```
--------------------------------
### Mini Icon Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/icons.md
Renders an icon from the Mini set by prefixing the icon name with 'm.'.
```php
->icon('m.academic-cap')
```
--------------------------------
### Initialize ThemeSwitcher Component (PHP)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/theme-switcher.md
Use this method to create an instance of the ThemeSwitcher component in your PHP code. No specific setup or imports are required beyond the namespace.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:1]
use MoonShine\UI\Components\Layout\ThemeSwitcher;
ThemeSwitcher::make()
```
--------------------------------
### Solid Icon Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/icons.md
Renders an icon from the Solid set by prefixing the icon name with 's.'.
```php
->icon('s.academic-cap')
```
--------------------------------
### Compact Icon Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/icons.md
Renders an icon from the Compact set by prefixing the icon name with 'c.'.
```php
->icon('c.academic-cap')
```
--------------------------------
### Repository Structure Example
Source: https://github.com/moonshine-software/doc/blob/4.x/CLAUDE.md
Illustrates the directory structure of the MoonShine documentation repository, detailing the organization of English and Russian documentation, resources, and configuration files.
```markdown
├── en/ # English documentation
│ ├── advanced/ # Advanced topics
│ ├── appearance/ # UI customization (menu, layout, assets, colors, icons)
│ ├── components/ # Component documentation
│ ├── fields/ # Field types documentation
│ ├── frontend/ # Frontend (JS, SDUI, API)
│ ├── model-resource/ # ModelResource documentation
│ ├── page/ # Pages documentation
│ ├── recipes/ # Code recipes and examples
│ ├── security/ # Authorization and authentication
│ └── _includes/ # Reusable markdown partials
├── ru/ # Russian documentation (mirrors en/ structure)
├── resources/
│ └── screenshots/ # Documentation screenshots
├── navigation.md # Documentation navigation structure
└── README.md # Documentation writing guidelines
```
--------------------------------
### Basic Icon Usage
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/icons.md
Use this for a simple icon from the default set (e.g., Outline). No special setup is required.
```php
->icon('cog')
```
--------------------------------
### Basic SDUI Structure Request
Source: https://github.com/moonshine-software/doc/blob/4.x/en/frontend/sdui.md
Send a GET request with the 'X-MS-Structure: true' header to retrieve the basic UI structure.
```http
GET /admin/dashboard HTTP/1.1
X-MS-Structure: true
```
--------------------------------
### Install MoonShine Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/advanced/commands.md
Command to install the MoonShine package in your Laravel project. Use options to customize the installation process.
```shell
php artisan moonshine:install
```
```shell
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
--------------------------------
### Install MoonShine Socialite
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authentication.md
Install the Socialite package for MoonShine using Composer.
```shell
composer require moonshine/socialite
```
--------------------------------
### Create BottomBar with Components (PHP)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/bottom-bar.md
Instantiate the BottomBar component using the make method, passing an array of components. This example shows how to include a Menu with a MenuItem.
```php
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\BottomBar;
use MoonShine\UI\Components\Layout\Menu;
BottomBar::make([
Menu::make([
MenuItem::make('/', 'Item')
]);
])
```
--------------------------------
### Initialize Head Component with Meta
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/head.md
Demonstrates how to initialize the Head component with custom meta tags using the make method. Requires importing the Head and Meta classes.
```php
use MoonShine\UI\Components\Layout\Head;
use MoonShine\UI\Components\Layout\Meta;
Head::make([
Meta::make('csrf-token')->customAttributes([
'content' => 'token',
]),
]);
```
```blade
```
--------------------------------
### Markdown Include Shortcode Example
Source: https://github.com/moonshine-software/doc/blob/4.x/CLAUDE.md
Demonstrates the usage of the `@include()` shortcode in Markdown for connecting partials with parameters, using `sprintf` formatting.
```markdown
@include('_includes/partial', 'param1', 'param2')
```
--------------------------------
### Initialize Sidebar with Components
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/sidebar.md
Use the `make` method to create a Sidebar instance and pass an array of components to its constructor. This example shows how to build a complex sidebar layout with header elements and a menu.
```php
use MoonShine\UI\Components\Layout\Sidebar;
Sidebar::make([
Fragment::make([
Div::make([
Logo::make(
'/',
'/vendor/moonshine/logo-small.svg',
)->minimized(),
])->class('menu-logo'),
Div::make([
Notifications::make(),
ThemeSwitcher::make(),
])->class('menu-actions'),
Div::make([
Burger::make()->sidebar(),
])->class('menu-burger'),
])->class('menu-header')->name('sidebar-top'),
Fragment::make([
Menu::make(),
])->customAttributes([
'class' => 'menu menu--vertical',
])->name('sidebar-content'),
])->collapsed()
```
```blade
```
--------------------------------
### Initialize Grid Component
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/grid.md
Use the `Grid::make` method to create a grid instance. Specify an iterable of components and an optional gap size between them.
```php
make(
iterable $components = [],
int $gap = 6,
)
```
--------------------------------
### Implement onLoad() in Model Resource
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/index.md
Integrate logic when a resource is loaded and active by implementing the `onLoad()` method. This can be used for various setup tasks.
```php
class PostResource extends ModelResource
{
// ...
protected function onLoad(): void
{
// ...
}
}
```
--------------------------------
### Set Up Authenticated User for Testing
Source: https://github.com/moonshine-software/doc/blob/4.x/en/advanced/testing.md
This setup method authenticates a MoonShine user for testing purposes. It creates a user via factory and authenticates them using the 'moonshine' guard.
```php
protected function setUp(): void
{
parent::setUp();
$user = MoonshineUser::factory()->create();
$this->be($user, 'moonshine');
}
```
--------------------------------
### Run Local Development Server
Source: https://github.com/moonshine-software/doc/blob/4.x/en/quick-start.md
Starts the local development server for your Laravel application. Access the admin panel at http://127.0.0.1:8000/admin.
```shell
php artisan serve
```
--------------------------------
### Initialize ActionGroup with Buttons
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-group.md
Create an ActionGroup and populate it with multiple ActionButton instances during initialization. Ensure ActionButton and ActionGroup are imported.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:2]
use MoonShine\UI\Components\ActionButton;
use MoonShine\UI\Components\ActionGroup;
ActionGroup::make([
ActionButton::make('Button 1'),
ActionButton::make('Button 2'),
])
```
--------------------------------
### Create a Basic Link
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/link.md
Use the `Link::make()` method to create a styled link. The first argument is the URL and the second is the link text. This is the basic setup for any link.
```php
Link::make('https://moonshine-laravel.com', 'Moonshine')
```
--------------------------------
### Install easymde Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/markdown.md
Use this Composer command to install the easymde package. Refer to the package repository for more details on its features.
```shell
composer require moonshine/easymde
```
--------------------------------
### Instantiate Files Component in PHP
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/files.md
Use the `Files::make()` method to create an instance of the Files component. Pass an array of file paths to display. The `$download` parameter controls the download functionality.
```php
make(
array $files = [],
bool $download = true,
)
```
--------------------------------
### Install MoonShine JWT Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/frontend/api.md
Install the JWT package for MoonShine using Composer. This enables token-based authentication for API interactions.
```shell
composer require moonshine/jwt
```
--------------------------------
### Grid and Column Example (Blade)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/grid.md
Illustrates creating a grid with two columns using Blade components. Each column is configured to span 6 units on all screen sizes.
```blade
{{ fake()->text() }}
{{ fake()->text() }}
```
--------------------------------
### Install Moonshine Ace Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/code.md
Use this Composer command to install the Moonshine Ace package. Refer to the package repository for more details.
```shell
composer require moonshine/ace
```
--------------------------------
### Install MoonShine OpenApi Generator
Source: https://github.com/moonshine-software/doc/blob/4.x/en/frontend/api.md
Install the OpenApi Generator package for MoonShine using Composer. This tool helps generate OpenAPI specifications for your API.
```shell
composer require moonshine/oag
```
--------------------------------
### AsyncMethod Attribute Examples
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/form-builder.md
Examples of PHP methods marked with the `AsyncMethod` attribute for secure asynchronous calls, including handling responses, redirects, and exceptions.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:1]
use MoonShine\Support\Attributes\AsyncMethod;
// With notification
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
return $response->toast('My message', ToastType::SUCCESS);
}
// Redirect
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
return $response->redirect('/');
}
// Redirect
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): RedirectResponse
{
return back();
}
// Exception
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): void
{
throw new \Exception('My message');
}
```
--------------------------------
### Implement onBoot() in Model Resource
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/index.md
Integrate logic when MoonShine is creating an instance of the resource by implementing the `onBoot()` method.
```php
class PostResource extends ModelResource
{
// ...
protected function onBoot(): void
{
// ...
}
}
```
--------------------------------
### Initialize TableBuilder with Items and Fields
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/table-builder.md
Create a TableBuilder instance and define its data items and fields for display.
```php
TableBuilder::make()
->items([
['id' => 1, 'title' => 'Hello world']
])
->fields([
ID::make()->sortable(),
Text::make('Title'),
])
```
--------------------------------
### Pull Request Checklist Example
Source: https://github.com/moonshine-software/doc/blob/4.x/CLAUDE.md
Example of a checklist used in a Pull Request template, including placeholders for issue numbers and language version checkboxes.
```markdown
- Issue #
- Lang
- [ ] En
- [ ] Ru
```
--------------------------------
### Markdown Alert Examples
Source: https://github.com/moonshine-software/doc/blob/4.x/CLAUDE.md
Provides examples of different alert types in Markdown: NOTE, WARNING, and TIP, using blockquote syntax with specific prefixes.
```markdown
> [!NOTE]
> Simple notification.
> [!WARNING]
> Warning.
> [!TIP]
> Tips.
```
--------------------------------
### Initialize Profile Component (Class)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/profile.md
Basic initialization of the Profile component using its make method.
```php
Profile::make()
```
--------------------------------
### REST API CrudResource Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/advanced/crud-resource.md
Example implementation of CrudResource for interacting with a REST API, including methods for fetching, finding, deleting, and saving data.
```php
namespace App\MoonShine\Resources;
use Illuminate\Support\Facades\Http;
use MoonShine\Contracts\Core\DependencyInjection\FieldsContract;
use MoonShine\Contracts\Core\TypeCasts\DataWrapperContract;
use MoonShine\Crud\Resources\CrudResource; // [tl! collapse:end]
final class RestCrudResource extends CrudResource
{
public function getItems(): iterable
{
yield from collect(Http::get('https://jsonplaceholder.typicode.com/todos')->json())
->map(fn ($item): DataWrapperContract => $this->getCaster()->cast($item))
->toArray();
}
public function findItem(bool $orFail = false): ?DataWrapperContract
{
return $this->getCaster()->cast(
Http::get('https://jsonplaceholder.typicode.com/todos/' . $this->getItemID())->json()
);
}
public function massDelete(array $ids): void
{
$this->beforeMassDeleting($ids);
foreach ($ids as $id) {
$this->delete($this->getCaster()->cast(['id' => $id]));
}
$this->afterMassDeleted($ids);
}
public function delete(DataWrapperContract $item, ?FieldsContract $fields = null): bool
{
return Http::delete('https://jsonplaceholder.typicode.com/todos/' . $item->getOriginal()['id'])->successful();
}
public function save(DataWrapperContract $item, ?FieldsContract $fields = null): DataWrapperContract
{
$originalItem = $item->getOriginal();
$data = request()->all();
if ($originalItem['id'] ?? false) {
return Http::put('https://jsonplaceholder.typicode.com/todos/' . $originalItem['id'], $data)->json();
}
$this->isRecentlyCreated = true;
return $this->getCaster()->cast(Http::post('https://jsonplaceholder.typicode.com/todos', $originalItem)->json());
}
}
```
--------------------------------
### Basic Settings: config/moonshine.php vs. ServiceProvider
Source: https://github.com/moonshine-software/doc/blob/4.x/en/configuration.md
Compare the configuration of basic MoonShine settings using the config/moonshine.php file and the MoonShineServiceProvider. These include directory, namespace, and system usage flags.
```php
'dir' => 'app/MoonShine',
'namespace' => 'App\MoonShine',
'use_migrations' => true,
'use_notifications' => true,
'use_database_notifications' => true,
```
```php
$config
->dir(dir: 'app/MoonShine', namespace: 'App\MoonShine')
->useMigrations()
->useNotifications()
->useDatabaseNotifications();
```
--------------------------------
### Get Colors and Shades
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/colors.md
Retrieve color values using `get()` and `getAll()`. You can specify the format (HEX or stored) and retrieve specific shades or all defined colors.
```php
$colorManager->get('primary'); // Returns HEX by default
```
```php
$colorManager->get('primary', hex: false); // Returns the stored format
```
```php
$colorManager->get('base', 500); // Get a specific shade
```
```php
$colorManager->getAll(); // For light theme
```
```php
$colorManager->getAll(dark: true); // For dark theme
```
--------------------------------
### Configuring Storage Disk and Options
Source: https://github.com/moonshine-software/doc/blob/4.x/en/configuration.md
Set the default disk for file storage and any associated options. Also configure the directory for user avatars.
```php
'disk' => 'public',
'disk_options' => [],
'user_avatars_dir' => 'moonshine_users',
```
```php
$config
->disk('public', options: [])
->userAvatarsDir('images/avatars');
```
--------------------------------
### PrettyLimit Field Integration Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/pretty-limit.md
Demonstrates how to apply the prettyLimit() method to a Text field. The color parameter is set to Color::PRIMARY. This modifies the field's display in preview mode.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:2]
use MoonShine\Support\Enums\Color;
use MoonShine\UI\Fields\Text;
Text::make('Title', 'title')
->prettyLimit(Color::PRIMARY);
```
--------------------------------
### Example Laravel Policy for MoonShine
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authorization.md
Define a policy class to manage permissions for a specific resource. This example shows a basic policy for the Post resource, allowing all actions by default.
```php
namespace App\Policies;
use App\Models\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
use MoonShine\Laravel\Models\MoonshineUser;
class PostPolicy
{
use HandlesAuthorization;
public function viewAny(MoonshineUser $user)
{
return true;
}
public function view(MoonshineUser $user, Post $model)
{
return true;
}
public function create(MoonshineUser $user)
{
return true;
}
public function update(MoonshineUser $user, Post $model)
{
return true;
}
public function delete(MoonshineUser $user, Post $model)
{
return true;
}
public function restore(MoonshineUser $user, Post $model)
{
return true;
}
public function forceDelete(MoonshineUser $user, Post $model)
{
return true;
}
public function massDelete(MoonshineUser $user)
{
return true;
}
}
```
--------------------------------
### PrettyLimit Basic Usage with Colors (PHP)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/pretty-limit.md
Demonstrates how to use the PrettyLimit component with different color options using the Color enum or string values.
```php
use MoonShine\Support\Enums\Color;
use MoonShine\UI\Components\PrettyLimit;
PrettyLimit::make('Long text that will be truncated', Color::PRIMARY);
PrettyLimit::make('Long text that will be truncated', Color::SECONDARY);
PrettyLimit::make('Long text that will be truncated', Color::SUCCESS);
PrettyLimit::make('Long text that will be truncated', Color::INFO);
PrettyLimit::make('Long text that will be truncated', Color::WARNING);
PrettyLimit::make('Long text that will be truncated', Color::ERROR);
// or strings
PrettyLimit::make('Long text that will be truncated', 'purple');
PrettyLimit::make('Long text that will be truncated', 'pink');
PrettyLimit::make('Long text that will be truncated', 'blue');
PrettyLimit::make('Long text that will be truncated', 'green');
PrettyLimit::make('Long text that will be truncated', 'yellow');
PrettyLimit::make('Long text that will be truncated', 'red');
PrettyLimit::make('Long text that will be truncated', 'gray');
```
--------------------------------
### Create Option and OptionGroup via Static Method
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/select.md
Use the static `make()` method for convenient creation of Option and OptionGroup objects. Ensure necessary imports are included.
```php
use MoonShine\Support\DTOs\Select\Option;
use MoonShine\Support\DTOs\Select\OptionGroup;
use MoonShine\Support\DTOs\Select\Options;
Option::make('Label', 'value')
OptionGroup::make('Group', new Options([
Option::make('Option 1', '1'),
Option::make('Option 2', '2'),
]))
```
--------------------------------
### Create Thumbnails with Class
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/thumbnails.md
Use the Thumbnails::make method to create a thumbnail component with a list of image paths.
```php
use MoonShine\UI\Components\Thumbnails;
Thumbnails::make([
'/images/image_1.jpg',
'/images/image_2.jpg',
'/images/image_3.jpg',
]),
```
--------------------------------
### CardsBuilder Title and URL Configuration
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Example configuring both the title and its associated URL for a card.
```php
CardsBuilder::make(
fields: [Text::make('Text')],
items: Article::paginate()
)
->title('title')
->url(fn($data) => $this->getFormPageUrl($data))
```
--------------------------------
### Update Dependencies
Source: https://github.com/moonshine-software/doc/blob/4.x/en/upgrade-guide.md
Run composer update to install the new MoonShine package version and its dependencies.
```shell
composer update
```
--------------------------------
### CardsBuilder Paginator Configuration
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Example of setting a custom paginator for CardsBuilder using ModelCaster and QueryBuilder.
```php
->paginator(
(new ModelCaster(Article::class))
->paginatorCast(
Article::query()->paginate()
)
)
```
--------------------------------
### Enable Modals for Create, Edit, and Detail
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/index.md
Configure a resource to open create, edit, and detail views within modal windows by setting boolean properties.
```php
class PostResource extends ModelResource
{
protected bool $createInModal = true;
protected bool $editInModal = true;
protected bool $detailInModal = true;
// ...
}
```
--------------------------------
### Create an ActionGroup
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-group.md
Instantiate an ActionGroup with an iterable of ActionButton instances. This is the basic setup for grouping buttons.
```php
ActionGroup::make(iterable $actions = [])
```
--------------------------------
### ActionButton with File Download
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-button.md
Shows how to configure an `ActionButton` to trigger a method that returns a file for download.
```php
ActionButton::make('ZIP')
->method('zip')
->download()
```
--------------------------------
### Install MoonShine via Composer
Source: https://github.com/moonshine-software/doc/blob/4.x/en/installation.md
Use this command to add MoonShine to your Laravel project using Composer.
```shell
composer require moonshine/moonshine
```
--------------------------------
### CardsBuilder Content and Fields Example
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/cards-builder.md
Shows CardsBuilder usage with custom content, fields, and paginated items.
```php
CardsBuilder::make(
fields: [Text::make('Text')],
items: Article::paginate()
)
->content('Custom content')
```
--------------------------------
### Basic Tabs Implementation
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/tabs.md
Demonstrates creating tabs using both the class-based approach with `Tabs` and `Tab` components, and the Blade component syntax with slots for content.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:3]
use MoonShine\UI\Components\Tabs;
use MoonShine\UI\Components\Tabs\Tab;
use MoonShine\UI\Fields\Text;
Tabs::make([
Tab::make('Tab 1', [
Text::make('Text 1')
]),
Tab::make('Tab 2', [
Text::make('Text 2')
]),
]),
```
```blade
Tab 1 content
Tab 2 content
Tab 3 content
```
--------------------------------
### Create ProgressBar Instance
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/progress-bar.md
Instantiate a ProgressBar component using the make method. Accepts value, size, color, and a radial option.
```php
make(
float|int $value,
string $size = 'sm',
string|Color $color = '',
bool $radial = false,
)
```
--------------------------------
### JWT Authentication
Source: https://github.com/moonshine-software/doc/blob/4.x/en/frontend/api.md
MoonShine provides JWT authentication for API interactions. After installation and configuration, you can authenticate via tokens.
```APIDOC
## JWT Authentication
### Description
Enables token-based authentication for API requests.
### Installation
```shell
composer require moonshine/jwt
php artisan vendor:publish --provider="MoonShine\JWT\Providers\JWTServiceProvider"
```
### Configuration
Add a base64 secret key to your `.env` file:
```ini
JWT_SECRET=YOUR_BASE64_SECRET_HERE
```
Update your `config/moonshine.php` to include JWT middleware:
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:2]
use MoonShine\JWT\JWTAuthPipe;
use MoonShine\JWT\Http\Middleware\AuthenticateApi;
return [
// ...
'auth' => [
// ...
'middleware' => [
AuthenticateApi::class,
],
'pipelines' => [
JWTAuthPipe::class
],
]
// ...
];
```
### Usage
Upon successful authentication, you will receive a token. Use this token in the `Authorization` header:
`Authorization: Bearer `
```
--------------------------------
### Install TinyMce Package
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/tinymce.md
Use Composer to add the TinyMce package to your project. Refer to the package repository for more details.
```shell
composer require moonshine/tinymce
```
--------------------------------
### Configure Theme Components
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/colors.md
Use component helpers like `background()`, `text()`, `borders()`, `button()`, `menu()`, `dropzone()`, and `form()` to configure related color variables for different UI components.
```php
$colorManager->background('oklch(91% 0 0)', pageBg: 'oklch(98% 0 0)');
```
```php
$colorManager->text('oklch(20% 0.04 274)');
```
```php
$colorManager->borders('oklch(72% 0.02 274)');
```
```php
$colorManager->button(
'oklch(65% 0.18 264)',
text: '#ffffff',
hoverBg: 'oklch(60% 0.18 264)',
hoverText: '#f8fafc'
);
```
```php
$colorManager->menu(
'oklch(70% 0.14 230)',
text: '#0f172a',
hoverBg: 'oklch(80% 0.05 230)'
);
```
```php
$colorManager->dropzone(
'oklch(98% 0 0)',
text: '#0f172a',
icon: '#2563eb'
);
```
```php
$colorManager->form(
bg: 'oklch(100% 0 0)',
text: '#0f172a',
focus: '#2563eb',
disabled: '#f1f5f9',
disabledText: '#64748b'
);
```
--------------------------------
### Retrieve Route from Resource Context
Source: https://github.com/moonshine-software/doc/blob/4.x/en/advanced/routes.md
Example of how to retrieve a route name, specifically 'permissions', from within the resource context.
```php
$this->getRoute('permissions')
```
--------------------------------
### Create Header Component
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/header.md
Instantiate the Header component using the make method, optionally passing an array of components to include.
```php
make(iterable $components = [])
```
```php
use MoonShine\UI\Components\Layout\Header;
Header::make([
Search::make(),
])
```
--------------------------------
### Get Main Detail Component
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/pages.md
Retrieve the main detail page component for output. This can be accessed directly or through a resource.
```php
$page->getDetailComponent();
```
```php
$resource->getDetailPage()->getDetailComponent();
```
--------------------------------
### Get Main Form Component
Source: https://github.com/moonshine-software/doc/blob/4.x/en/model-resource/pages.md
Retrieve the main form page component for output. This can be accessed directly or through a resource.
```php
$page->getFormComponent();
```
```php
$resource->getFormPage()->getFormComponent();
```
--------------------------------
### Create a Number Field (Class)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/number.md
Instantiate a Number field using its class. This is the basic setup for a numeric input.
```php
use MoonShine\UI\Fields\Number;
Number::make('Sort')
```
--------------------------------
### Async Select with AsyncMethod
Source: https://github.com/moonshine-software/doc/blob/4.x/en/recipes/select.md
Use the `async()` method with `asyncOnInit()` for initial data loading. The implementation is placed directly in the resource using `AsyncMethod`.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:start]
use MoonShine\Crud\JsonResponse;
use MoonShine\Support\Attributes\AsyncMethod; // [tl! collapse:end]
protected function formFields(): iterable
{
return [
Select::make('Select')->async(
$this->getAsyncMethodUrl('selectOptions')
)->asyncOnInit(),
]
}
#[AsyncMethod]
public function selectOptions(): JsonResponse
{
$options = new Options([
new Option(label: 'Option 1', value: '1', selected: true, properties: new OptionProperty(image: 'https://cutcode.dev/images/platforms/youtube.png')),
new Option(label: 'Option 2', value: '2', properties: new OptionProperty(image: 'https://cutcode.dev/images/platforms/youtube.png')),
]);
return JsonResponse::make(data: $options->toArray());
}
```
--------------------------------
### Implement Action Button with Confirmation
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-button.md
Example of creating an action button that triggers a confirmation modal before executing its action. Ensure a unique 'name' is provided if using multiple similar modals.
```php
ActionButton::make('Button Label')
->withConfirm(
title: 'Confirmation Modal Window Title',
content: 'Confirmation Modal Window Content',
button: 'Confirmation Modal Window Button',
// optionally - additional form fields
fields: null,
method: HttpMethod::POST,
// optionally - closure with FormBuilder
formBuilder: null,
// optionally - closure with Modal
modalBuilder: null,
name: 'my-modal',
)
```
--------------------------------
### Render Field Preview Before Rendering
Source: https://github.com/moonshine-software/doc/blob/4.x/en/fields/basic-methods.md
This example demonstrates using `beforeRender` to display a preview of the field's current value before the main field output. It requires the `Field` class and assumes a `preview()` method is available.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:1]
use MoonShineleday
Text::make('Title')
->beforeRender(function(Field $field) {
return $field->preview();
})
```
--------------------------------
### Override Logout Redirect
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authentication.md
Customize the redirect behavior after a user logs out. This example redirects to the application's root URL.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:start]
use Closure;
use Symfony\Component\HttpFoundation\Response; // [tl! collapse:end]
$config->logoutUsing(function (Closure $default): Response {
// Custom redirect after logout
return redirect()->to('/');
// Or use the default behavior
// return $default();
});
```
--------------------------------
### Initialize Search Component (Class)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/search.md
Use this to create a new instance of the Search component using the Class API.
```php
Search::make()
```
--------------------------------
### Override Authentication Redirect
Source: https://github.com/moonshine-software/doc/blob/4.x/en/security/authentication.md
Customize the redirect behavior after a successful authentication. This example shows how to redirect to a specific dashboard route.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:start]
use Closure;
use Symfony\Component\HttpFoundation\Response; // [tl! collapse:end]
$config->authenticateUsing(function (Closure $default): Response {
// Custom redirect after login
return redirect()->to('/dashboard');
// Or use the default behavior
// return $default();
});
```
--------------------------------
### ArticleFormPage Structure
Source: https://github.com/moonshine-software/doc/blob/4.x/en/recipes/tabs.md
Example of a complete MoonShine FormPage class, demonstrating the organization of fields, relationship methods, and tabbed layers.
```php
final class ArticleFormPage extends FormPage
{
protected function fields(): iterable
{
return [
ID::make(),
// ...
$this->getCommentsField(),
$this->getCommentField(),
];
}
private function getCommentsField(): HasMany
{
return HasMany::make('Comments', resource: CommentResource::class)
->fillData($this->getResource()->getItem())
->async()
->creatable();
}
private function getCommentField(): HasOne
{
return HasOne::make('Comment', resource: CommentResource::class)
->fillData($this->getResource()->getItem())
->async();
}
protected function mainLayer(): array
{
return [
Tabs::make([
Tab::make('Basics', parent::mainLayer()),
Tab::make('Comments', [
$this->getResource()->getItem() ? $this->getCommentsField() : 'To add comments, save the article',
]),
Tab::make('Comment', [
$this->getResource()->getItem() ? $this->getCommentField() : 'To add comments, save the article',
]),
Tab::make('Table', [
TableBuilder::make()
->fields([
ID::make(),
Text::make('Text')
])
->cast(new ModelCaster(Comment::class))
->items($this->getResource()->getItem()?->comments ?? [])
]),
]),
];
}
protected function bottomLayer(): array
{
return [];
}
}
```
--------------------------------
### Create a Basic Modal using PHP Class
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/modal.md
Use the static `make()` method to create a modal instance. Requires title and content. External trigger and async URL are optional.
```php
use MoonShine\UI\Components\Modal;
Modal::make(
title: 'Confirm',
content: 'Content'
)
```
--------------------------------
### Global Color Override with ServiceProvider
Source: https://github.com/moonshine-software/doc/blob/4.x/en/appearance/colors.md
Use the `boot` method in your `MoonShineServiceProvider` to register a custom color palette and set primary and success background colors globally. Ensure that individual layouts do not override these global settings.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:start]
use Illuminate\Support\ServiceProvider;
use MoonShine\ColorManager\ColorManager;
use MoonShine\Contracts\ColorManager\ColorManagerContract;
use MoonShine\Contracts\Core\DependencyInjection\CoreContract;
use MoonShine\Contracts\Core\DependencyInjection\ConfiguratorContract;
use MoonShine\Laravel\DependencyInjection\MoonShine;
use MoonShine\Laravel\DependencyInjection\MoonShineConfigurator; // [tl! collapse:end]
class MoonShineServiceProvider extends ServiceProvider
{
/**
* @param MoonShine $core
* @param MoonShineConfigurator $config
* @param ColorManager $colors
*
*/
public function boot(
CoreContract $core,
ConfiguratorContract $config,
ColorManagerContract $colors,
): void
{
$colors->palette(new \App\MoonShine\Palettes\CorporatePalette());
$colors->primary('oklch(65% 0.18 264)');
$colors->successBg('oklch(70% 0.15 142)');
}
}
```
--------------------------------
### Update Profile Fragment from Controller
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/profile.md
Example of updating the 'profile' fragment from a controller method using JsonResponse and AlpineJs events.
```php
public function saveElement(CrudRequestContract $request): JsonResponse
{
// ...
return JsonResponse::make()->events([
AlpineJs::event(JsEvent::FRAGMENT_UPDATED, 'profile'),
]);
}
```
--------------------------------
### JSON Response for Notifications
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/action-button.md
Example JSON structure for returning notifications (toast messages) and optional redirects from an asynchronous request.
```json
{
"message": "Toast",
"messageType": "success",
"redirect": "/url"
}
```
--------------------------------
### Create Menu with Class and MenuItem
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/menu.md
Demonstrates creating a menu using the Menu class and MenuItem objects in PHP. This is useful for programmatic menu construction.
```php
// torchlight! {"summaryCollapsedIndicator": "namespaces"}
// [tl! collapse:2]
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\Menu;
Menu::make([
MenuItem::make('/', 'Item')
]);
```
--------------------------------
### DataWrapperContract Interface
Source: https://github.com/moonshine-software/doc/blob/4.x/en/advanced/type-casts.md
Defines the contract for wrapping data, providing methods to get the original data, its key, and convert it to an array.
```php
interface DataWrapperContract
{
public function getOriginal(): mixed;
public function getKey(): int|string|null;
public function toArray(): array;
}
```
--------------------------------
### PrettyLimit with Label (PHP)
Source: https://github.com/moonshine-software/doc/blob/4.x/en/components/pretty-limit.md
Illustrates adding a label to the PrettyLimit component using the constructor or the 'label' method.
```php
use MoonShine\Support\Enums\Color;
use MoonShine\UI\Components\PrettyLimit;
PrettyLimit::make('Tariff name with long description', Color::PRIMARY, '2 weeks');
// or via method
PrettyLimit::make('Tariff name with long description')
->color(Color::SUCCESS)
->label('Active');
```