### Configure MoonShine
Source: https://getmoonshine.app/en/docs/4.x/quick-start
Runs the MoonShine installation command with the -Q flag for a quick setup.
```bash
php artisan moonshine:install -Q
```
--------------------------------
### Run Artisan Commands for Setup
Source: https://getmoonshine.app/en/docs/4.x/contribution
Execute a series of Artisan commands to generate an application key, create storage symlinks, run database migrations and seeds, create a MoonShine user, and start the development server.
```bash
php artisan key:generate
php artisan storage:link
php artisan migrate --seed
php artisan moonshine:user
php artisan serve
```
--------------------------------
### Install Laravel with MoonShine Starter Kit
Source: https://getmoonshine.app/en/docs/4.x/quick-start
Installs Laravel and MoonShine together using a starter kit command.
```bash
laravel new example-app --using=moonshine/app
```
--------------------------------
### Install Laravel
Source: https://getmoonshine.app/en/docs/4.x/quick-start
Installs the Laravel installer globally and creates a new Laravel application.
```bash
composer global require laravel/installer
laravel new example-app
cd example-app
```
--------------------------------
### Get Form via Helper
Source: https://getmoonshine.app/en/docs/4.x/configuration
Example of retrieving a form instance using the `moonshineConfig()` helper function.
```php
$form = moonshineConfig()->getForm('login');
```
--------------------------------
### toPage Helper Examples
Source: https://getmoonshine.app/en/docs/4.x/model-resource/routes
Examples demonstrating various ways to use the toPage helper with different arguments.
```php
toPage(page: CustomPage::class);
toPage(page: IndexPage::class, resource: PostResource::class);
toPage(page: CustomPage::class, redirect: true);
toPage(page: CustomPage::class, fragment: true);
```
--------------------------------
### Get Page via Helper
Source: https://getmoonshine.app/en/docs/4.x/configuration
Example of retrieving a page instance using the `moonshineConfig()` helper function.
```php
$customPage = moonshineConfig()->getPage('custom');
```
--------------------------------
### Grid and Column Example (PHP)
Source: https://getmoonshine.app/en/docs/4.x/components/grid
Example of using Grid and Column components programmatically in PHP to create a two-column layout.
```PHP
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
),
])
```
```PHP
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
),
])
```
```PHP
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
),
])
```
```PHP
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
),
])
```
```PHP
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 MoonShine with Options
Source: https://getmoonshine.app/en/docs/4.x/advanced/commands
Installs the MoonShine package with various configuration options. Allows customization of the installation process, such as skipping user creation or migrations.
```bash
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
```bash
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
```bash
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
```bash
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
```bash
moonshine:install {--u|without-user} {--m|without-migrations} {--l|default-layout} {--a|without-auth} {--d|without-notifications} {--t|tests-mode} {--Q|quick-mode}
```
--------------------------------
### Example Post Policy Implementation
Source: https://getmoonshine.app/en/docs/4.x/model-resource/authorization
This example demonstrates a basic policy for the Post resource, defining methods for various actions like viewing, creating, updating, and deleting. All methods are set to return true, granting access 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;
}
}
```
--------------------------------
### Async Method Examples with DI and Attributes
Source: https://getmoonshine.app/en/docs/4.x/components/form-builder
Demonstrates various implementations of async methods, including those using Dependency Injection (DI) and the AsyncMethod attribute for security. Examples cover notifications, redirects, and exception handling.
```php
use MoonShine\{Support\Attributes\AsyncMethod, Http\Requests\CrudRequestContract, Http\Responses\JsonResponse, Http\Responses\RedirectResponse};
use MoonShine\Enums\ToastType;
// 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');
}
```
--------------------------------
### Basic Profile Menu Setup
Source: https://getmoonshine.app/en/docs/4.x/components/profile
Demonstrates how to create a basic menu for the Profile component using ActionButton.
```php
Profile::make()->menu([
ActionButton::make('Dashboard', '/admin')->icon('home-modern'),
])
```
--------------------------------
### Install Moonshine (Success)
Source: https://getmoonshine.app/en/docs/4.x/components/snippet
Use this snippet to install Moonshine with a success color indicator.
```bash
composer require moonshine/moonshine
```
--------------------------------
### AsyncMethod Example: Redirect
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
An example of an asynchronous method that performs a redirect.
```php
use MoonShine\Contracts\െCrudRequestContract;
use MoonShine\Support\Attributes\AsyncMethod;
use MoonShine\JsonResponse;
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
return $response->redirect('/');
}
```
--------------------------------
### Install Two-Factor Authentication Package
Source: https://getmoonshine.app/en/docs/4.x/security/authentication
Install the MoonShine two-factor authentication package using Composer.
```bash
composer require moonshine/two-factor
```
--------------------------------
### Clone Demo Project
Source: https://getmoonshine.app/en/docs/4.x/contribution
Clone the demo project to start your development. This is the initial step for setting up the project environment.
```bash
git clone git@github.com:moonshine-software/demo-project.git .
```
--------------------------------
### Install MoonShine Panel
Source: https://getmoonshine.app/en/docs/4.x/installation
Run this Artisan command after installing the package to set up the MoonShine admin panel. This command initiates the configuration process.
```bash
php artisan moonshine:install
```
--------------------------------
### Run the Local Server
Source: https://getmoonshine.app/en/docs/4.x/quick-start
Starts the local development server for your Laravel project.
```bash
php artisan serve
```
--------------------------------
### Basic TableBuilder Usage
Source: https://getmoonshine.app/en/docs/4.x/components/table-builder
Demonstrates the fundamental setup of the TableBuilder with items and fields.
```php
TableBuilder::make()
->items([
['id' => 1, 'title' => 'Hello world']
])
->fields([
ID::make()->sortable(),
Text::make('Title'),
])
```
--------------------------------
### Get Page via Dependency Injection
Source: https://getmoonshine.app/en/docs/4.x/configuration
Example of retrieving a page instance using dependency injection within a controller method.
```php
use MoonShine\Contracts\Core\DependencyInjection\ConfiguratorContract;
use MoonShine\Laravel\DependencyInjection\MoonShineConfigurator;
public function index(ConfiguratorContract $config)
{
$customPage = $config->getPage('custom');
}
```
--------------------------------
### Grid and Column Example (Blade)
Source: https://getmoonshine.app/en/docs/4.x/components/grid
Example of using Grid and Column components with Blade syntax to create a two-column layout.
```Blade
{{ fake()->text() }}
{{ fake()->text() }}
```
```Blade
{{ fake()->text() }}
{{ fake()->text() }}
```
```Blade
{{ fake()->text() }} {{ fake()->text() }}
```
```Blade
{{ fake()->text() }}
{{ fake()->text() }}
```
```Blade
{{ fake()->text() }} {{ fake()->text() }}
```
--------------------------------
### Install moonshine/scout Package
Source: https://getmoonshine.app/en/docs/4.x/model-resource/search
Install the moonshine/scout package using Composer. This is the first step to enable global search.
```bash
composer require moonshine/scout
```
--------------------------------
### Install OpenApi Generator
Source: https://getmoonshine.app/en/docs/4.x/frontend/api
Use Composer to install the moonshine/oag package.
```bash
composer require moonshine/oag
```
--------------------------------
### AsyncMethod Example: Back Redirect
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
An example of an asynchronous method that redirects to the previous page.
```php
use MoonShine\Contracts\െCrudRequestContract;
use MoonShine\Support\Attributes\AsyncMethod;
use MoonShine\RedirectResponse;
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): RedirectResponse
{
return back();
}
```
--------------------------------
### Displaying a Compact Icon
Source: https://getmoonshine.app/en/docs/4.x/appearance/icons
Use the `icon()` helper to render icons. This example shows how to display a compact icon.
```html
->icon('c.academic-cap')
```
--------------------------------
### Menu Translation File Example
Source: https://getmoonshine.app/en/docs/4.x/appearance/menu
Example of a Laravel translation file for menu items.
```php
// lang/en/menu.php
return [
'Comments' => 'Comments',
];
```
--------------------------------
### Install Import/Export Dependency
Source: https://getmoonshine.app/en/docs/4.x/model-resource/import-export
Install the MoonShine import-export package using Composer.
```bash
composer require moonshine/import-export
```
--------------------------------
### Install ApexCharts Package
Source: https://getmoonshine.app/en/docs/4.x/components/metrics
Install the `moonshine/apexcharts` package via Composer to enable interactive line and donut charts for your metrics.
```bash
composer require moonshine/apexcharts
```
--------------------------------
### Example Config File Content
Source: https://getmoonshine.app/en/docs/4.x/recipes/change-config
This shows the expected content of the generated `config/test.php` file after the form fields have been saved.
```php
return [
'var' => 'foo',
'bar' => 'test',
];
```
```php
return [
'var' => 'foo',
'bar' => 'test',
];
```
```php
return [
'var' => 'foo',
'bar' => 'test',
];
```
```php
return [
'var' => 'foo',
'bar' => 'test',
];
```
--------------------------------
### FormBuilder Usage Examples
Source: https://getmoonshine.app/en/docs/4.x/components/form-builder
Shows two ways to instantiate and configure FormBuilder: directly with arguments or using chained methods.
```php
FormBuilder::make(
action:'/crud/update',
method: FormMethod::POST,
fields: [
Hidden::make('_method')->setValue('put'),
Text::make('Text')
],
values: ['text' => 'Value']
)
// or
FormBuilder::make()
->action('/crud/update')
->method(FormMethod::POST)
->fields([
Hidden::make('_method')->setValue('put'),
Text::make('Text')
])
->fill(['text' => 'Value'])
```
--------------------------------
### Install MoonShine Socialite Package
Source: https://getmoonshine.app/en/docs/4.x/security/authentication
Install the Socialite package for MoonShine using Composer.
```bash
composer require moonshine/socialite
```
--------------------------------
### AsyncMethod Example: Success Notification
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
An example of an asynchronous method that returns a success notification.
```php
use MoonShine\{Contracts\െCrudRequestContract, Support\െAttributes\AsyncMethod};
use MoonShine\{JsonResponse, ToastType};
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request, JsonResponse $response): JsonResponse
{
// $request->getResource();
// $request->getResource()->getItem();
// $request->getPage();
return $response->toast('My message', ToastType::SUCCESS);
}
```
--------------------------------
### Add MoonShine Package and Install Dependencies
Source: https://getmoonshine.app/en/docs/4.x/contribution
Navigate to the packages directory, clone the MoonShine repository, and install its composer and npm dependencies. This ensures all necessary components are available.
```bash
cd packages && git clone git@github.com:moonshine-software/moonshine.git && cd moonshine && composer install && npm install
```
--------------------------------
### Example Policy Methods
Source: https://getmoonshine.app/en/docs/4.x/model-resource/authorization
These are standard policy methods that can be implemented for various authorization checks.
```php
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;
}
}
```
```php
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;
}
}
```
--------------------------------
### Example: Calling Submit Event on Form Page
Source: https://getmoonshine.app/en/docs/4.x/components/form-builder
An example of dispatching the `FORM_SUBMIT` event when creating form buttons.
```php
protected function formButtons(): ListOf
{
return parent::formButtons()
->add(
ActionButton::make('Save')
->dispatchEvent(AlpineJs::event(JsEvent::FORM_SUBMIT, $this->uriKey()))
);
}
```
--------------------------------
### Basic Form Example
Source: https://getmoonshine.app/en/docs/4.x/components/form-builder
Demonstrates a simple form with a text input and submit/cancel buttons.
```blade
Cancel
Submit
```
--------------------------------
### Create a ValueMetric Component
Source: https://getmoonshine.app/en/docs/4.x/components/metrics
Use the make method to create a ValueMetric instance with a label. This is the basic setup for displaying a single value.
```php
use MoonShine\UI\Components\Metrics\Wrapped\ValueMetric;
ValueMetric::make('Completed orders')
->value(fn() => Order::completed()->count())
```
--------------------------------
### Get Form via Dependency Injection
Source: https://getmoonshine.app/en/docs/4.x/configuration
Example of retrieving a form instance using dependency injection within a controller method.
```php
use MoonShine\Contracts\Core\DependencyInjection\ConfiguratorContract;
use MoonShine\Laravel\DependencyInjection\MoonShineConfigurator;
public function index(ConfiguratorContract $config)
{
$form = $config->getForm('login');
}
```
--------------------------------
### Flex Component Alignment
Source: https://getmoonshine.app/en/docs/4.x/components/flex
Control element alignment within the Flex component using the justifyAlign() and itemsAlign() methods. This example aligns items between and to the start.
```PHP
Flex::make([
Text::make('Test'),
Text::make('Test 2'),
])
->justifyAlign('between')
->itemsAlign('start')
```
--------------------------------
### Implementing a Custom CrudResource
Source: https://getmoonshine.app/en/docs/4.x/advanced/crud-resource
Extend CrudResource and implement abstract methods to create a custom resource. This example shows a RestCrudResource with methods for finding, getting, mass deleting, deleting, and saving items.
```php
namespace App\MoonShine\Resources;
use Illuminate\Contracts\Pagination\CursorPaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use MoonShine\Contracts\Core\DependencyInjection\FieldsContract;
use MoonShine\Crud\Resources\CrudResource;
use MoonShine\Contracts\Core\TypeCasts\DataWrapperContract;
final class RestCrudResource extends CrudResource
{
public function findItem(bool $orFail = false): ?DataWrapperContract
{
// ...
}
public function getItems(): iterable|Collection|LazyCollection|CursorPaginator|Paginator;
{
// ...
}
public function massDelete(array $ids): void
{
// ...
}
public function delete(DataWrapperContract $item, ?FieldsContract $fields = null): bool
{
// ...
}
public function save(DataWrapperContract $item, ?FieldsContract $fields = null): DataWrapperContract
{
// ...
}
}
```
--------------------------------
### Profile Component Initialization
Source: https://getmoonshine.app/en/docs/4.x/components/profile
Initialize the Profile component using the `make` method. This is a basic instantiation without specific parameters.
```php
Profile::make()
```
```php
Profile::make()
```
```php
Profile::make()
```
```php
Profile::make()
```
--------------------------------
### Basic Blade Layout Example
Source: https://getmoonshine.app/en/docs/4.x/appearance/layout
This snippet demonstrates a fundamental MoonShine Blade layout. It includes essential components like HTML structure, head with meta tags and assets, body, wrapper, sidebar, header, and content areas. Use this as a starting point for your custom templates.
```blade
@vite([
'resources/css/main.css',
'resources/js/app.js',
], 'vendor/moonshine')
Your content
```
--------------------------------
### Instantiate Files Component with File Paths
Source: https://getmoonshine.app/en/docs/4.x/components/files
Demonstrates how to create an instance of the Files component with a list of image file paths. Ensure the `MoonShine\UI\Components\Files` class is imported.
```php
use MoonShine\UI\Components\Files;
Files::make([
'/images/thumb_1.jpg',
'/images/thumb_2.jpg',
'/images/thumb_3.jpg',
]),
```
--------------------------------
### Layout Component Usage (PHP)
Source: https://getmoonshine.app/en/docs/4.x/components/layout
Demonstrates the basic usage of the Layout component in PHP. This is the starting point for creating custom layouts.
```php
namespace App\MoonShine\Layouts;
use MoonShine\UI\Components\Layout\Layout;
final class MoonShineLayout extends AppLayout
{
public function build(): Layout
{
return Layout::make([
// ...
]);
}
}
```
```php
namespace App\MoonShine\Layouts;use MoonShine\UI\Components\Layout\Layout;final class MoonShineLayout extends AppLayout{ public function build(): Layout { return Layout::make([ // ... ]); }}
```
--------------------------------
### Install Moonshine Fields Package
Source: https://getmoonshine.app/en/docs/4.x/fields/code
Use this command to install the Moonshine fields package via Composer. Ensure you have Composer installed and configured.
```bash
composer require moonshine/ace
```
--------------------------------
### Basic Icon Usage
Source: https://getmoonshine.app/en/docs/4.x/components/icon
Demonstrates the basic usage of the Icon component with its name. The `make` method is used to create an icon instance.
```php
use MoonShine\UI\Components\Icon;
Icon::make('users')
```
--------------------------------
### Set Up Authenticated User for Testing
Source: https://getmoonshine.app/en/docs/4.x/advanced/testing
This setup method demonstrates how to authenticate a MoonShine user for testing purposes by creating a user and authenticating them using the `be` method with the 'moonshine' guard.
```php
protected function setUp(): void
{
parent::setUp();
$user = MoonshineUser::factory()->create();
$this->be($user, 'moonshine');
}
```
--------------------------------
### Basic Img Component Usage
Source: https://getmoonshine.app/en/docs/4.x/components/img
Demonstrates the fundamental way to create an Img component instance with a source path.
```php
use MoonShine\UI\Components\Img;
Img::make('path_to_file');
```
--------------------------------
### AsyncMethod Example: Exception Handling
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
An example of an asynchronous method that throws an exception.
```php
use MoonShine\Contracts\െCrudRequestContract;
use MoonShine\Support\Attributes\AsyncMethod;
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request): void
{
throw new \Exception('My message');
}
```
--------------------------------
### Basic Box Component Usage (Class)
Source: https://getmoonshine.app/en/docs/4.x/components/box
Demonstrates the basic instantiation of the Box component using class syntax. Use this to highlight general content areas.
```php
use MoonShine\UI\Components\Layout\Box;
use MoonShine\UI\Components\Alert;
Box::make([
Alert::make()->content('Text')
]);
```
--------------------------------
### Run Migrations
Source: https://getmoonshine.app/en/docs/4.x/security/authentication
Execute Artisan migrations to set up the necessary database tables for Socialite.
```bash
php artisan migrate
```
--------------------------------
### Basic Menu Configuration
Source: https://getmoonshine.app/en/docs/4.x/appearance/menu
Example of configuring a menu array within the `menu()` method of an `AppLayout` class. It demonstrates adding menu items for a resource, a home route, and external links.
```php
use MoonShine\MenuManager\MenuItem;
protected function menu(): array {
return [
MenuItem::make(MoonShineUserResource::class),
MenuItem::make(fn() => route('home'), 'Home'),
MenuItem::make('https://moonshine-laravel.com/docs', 'Docs', blank: true),
MenuItem::make('https://laravel.com/docs', 'Laravel Docs', blank: true),
];
}
```
--------------------------------
### Install Markdown Field
Source: https://getmoonshine.app/en/docs/4.x/fields/markdown
Install the easymde package using Composer. This command adds the necessary package to your project.
```bash
composer require moonshine/easymde
```
--------------------------------
### Install MoonShine Package
Source: https://getmoonshine.app/en/docs/4.x/advanced/commands
Command to install the MoonShine package into your Laravel project. Use this to set up the admin panel.
```bash
php artisan moonshine:install
```
```bash
php artisan moonshine:install
```
```bash
php artisan moonshine:install
```
```bash
php artisan moonshine:install
```
```bash
php artisan moonshine:install
```
--------------------------------
### Example Nested JSON Data
Source: https://getmoonshine.app/en/docs/4.x/fields/json
This is an example of a JSON object representing product data with nested pricing information.
```json
[
{
"name": "product 1",
"prices": {
"wholesale_price": 1000,
"retail_price": 1200
}
}
]
```
--------------------------------
### Get All Colors for Themes
Source: https://getmoonshine.app/en/docs/4.x/appearance/colors
Retrieve all defined colors, with options to get them for the light theme (default) or the dark theme.
```php
// Get all colors
$colorManager->getAll(); // For light theme
$colorManager->getAll(dark: true); // For dark theme
```
--------------------------------
### Async Select with Custom Options
Source: https://getmoonshine.app/en/docs/4.x/recipes/select
Demonstrates using the `async()` method with `asyncOnInit()` for a Select component. It also shows how to define an asynchronous method to fetch options with custom properties like images.
```php
use MoonShine\Crud\JsonResponse;
use MoonShine\Support\Attributes\AsyncMethod;
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());
}
```
--------------------------------
### Basic ActionButton Method Call
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
Demonstrates how to create an ActionButton and specify a method to be called.
```php
ActionButton::make('Button Label')
->method('updateSomething')
```
--------------------------------
### Example SDUI Response Structure
Source: https://getmoonshine.app/en/docs/4.x/frontend/sdui
This is an example of a JSON response for a Dashboard component, illustrating the nested structure of components and their attributes.
```json
{
"type": "Dashboard",
"components": [
{
"type": "Card",
"components": [
{
"type": "Heading",
"attributes": {
"class": ["text-2xl", "font-bold"],
"id": "dashboard-heading"
}
},
{
"type": "Text",
"attributes": {
"class": ["mt-2", "text-gray-600"]
}
}
],
"attributes": {
"class": ["bg-white", "shadow", "rounded-lg"],
"data-card-id": "dashboard-overview"
}
}
],
"attributes": {
"class": ["container", "mx-auto", "py-6"]
}
}
```
--------------------------------
### AsyncMethod Example: Custom JSON Response
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
An example of an asynchronous method returning a custom JSON response with HTML content.
```php
use MoonShine\Contracts\െCrudRequestContract;
use MoonShine\Support\Attributes\AsyncMethod;
use MoonShine\JsonResponse;
#[AsyncMethod]
public function updateSomething(CrudRequestContract $request)
{
return JsonResponse::make()->html('Content');
}
```
--------------------------------
### Configure Authentication Pipeline using Facade
Source: https://getmoonshine.app/en/docs/4.x/security/authentication
Alternatively, configure the authentication pipeline using the facade in your service provider.
```php
$config->authPipelines([
MoonShine woFactor woFactorAuthPipe::class
]);
```
--------------------------------
### Initialize Search Component
Source: https://getmoonshine.app/en/docs/4.x/components/search
Basic initialization of the Search component using the Search::make() method.
```php
Search::make()
Search::make()
Search::make()
Search::make()
```
--------------------------------
### Basic Logo Component Usage (PHP)
Source: https://getmoonshine.app/en/docs/4.x/components/logo
Demonstrates how to create a Logo component instance using the make method in PHP. This is useful for programmatically adding the logo to your layout.
```PHP
use MoonShine\UI\Components\Layout\Logo;
Logo::make(
'/admin',
'/vendor/moonshine/logo.svg',
'/vendor/moonshine/logo-small.svg'
)
```
--------------------------------
### HTML Color Output Example
Source: https://getmoonshine.app/en/docs/4.x/appearance/colors
An example of the generated HTML output for color variables, including light and dark themes.
```html
```
--------------------------------
### Install TinyMCE Package
Source: https://getmoonshine.app/en/docs/4.x/fields/tinymce
Use Composer to install the TinyMCE package for Moonshine. This command should be run in your project's root directory.
```bash
composer require moonshine/tinymce
```
--------------------------------
### Using Color Shortcuts
Source: https://getmoonshine.app/en/docs/4.x/appearance/colors
Demonstrates the use of dynamic methods provided by ColorShortcuts for adjusting groups of color variables.
```php
$colorManager->primary('oklch(65% 0.18 264)', text: '#ffffff');
$colorManager->success('oklch(63.9% 0.218 142.495)', text: '#194638', everything: true);
$colorManager->collapse(
'oklch(100% 0 0)',
text: '#0f172a',
bgOpen: 'oklch(96% 0 0)'
);
$colorManager->progress(
bg: 'oklch(96% 0 0)',
barBg: 'oklch(65% 0.18 264)',
text: '#0f172a'
);
$colorManager->theme('oklch(95% 0.01 274)', 400);
$colorManager->theme('oklch(35% 0.18 274)', 800, dark: true);
```
--------------------------------
### Example SDUI Dashboard Response
Source: https://getmoonshine.app/en/docs/4.x/frontend/sdui
This is an example of a JSON response that defines a dashboard structure. It includes cards, headings, and text components.
```json
{
"type": "Dashboard",
"components": [
{
"type": "Card",
"components": [
{
"type": "Heading",
"states": {
"level": 1,
"content": "Welcome to Dashboard"
},
"attributes": {
"class": ["text-2xl", "font-bold"],
"id": "dashboard-heading"
}
},
{
"type": "Text",
"states": {
"content": "Here's an overview of your system."
},
"attributes": {
"class": ["mt-2", "text-gray-600"]
}
}
],
"states": {
"title": "Dashboard Overview"
},
"attributes": {
"class": ["bg-white", "shadow", "rounded-lg"],
"data-card-id": "dashboard-overview"
}
}
],
"states": {
"title": "Admin Dashboard"
},
"attributes": {
"class": ["container", "mx-auto", "py-6"]
}
}
```
--------------------------------
### Create Components Instance
Source: https://getmoonshine.app/en/docs/4.x/components/components
Instantiate the Components component. It accepts an array of components as an argument.
```php
use MoonShine\UI\Components\Components;
Components::make([
// components
]);
```
--------------------------------
### PrettyLimit with Label and Color
Source: https://getmoonshine.app/en/docs/4.x/components/pretty-limit
Demonstrates creating a PrettyLimit component with a specified color and label. This is useful for adding contextual information to text.
```php
use MoonShine\Support\Enums\Color;
use MoonShine\UI\Components\PrettyLimit;
PrettyLimit::make('Tariff name with long description', Color::PRIMARY, '2 weeks');
```
```php
use MoonShine\Support\Enums\Color;
use MoonShine\UI\Components\PrettyLimit;
PrettyLimit::make('Tariff name with long description')
->color(Color::SUCCESS)
->label('Active');
```
--------------------------------
### Install MoonShine JWT Package
Source: https://getmoonshine.app/en/docs/4.x/frontend/api
Install the JWT package using Composer. This is the first step to enable JWT authentication for your MoonShine application.
```bash
composer require moonshine/jwt
```
--------------------------------
### MoonShine Configuration File Example
Source: https://getmoonshine.app/en/docs/4.x/configuration
This snippet shows the typical structure and available settings within the `config/moonshine.php` file. Modify these values to customize your application's behavior.
```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'],
// ...
];
```
--------------------------------
### Get Color and Shades
Source: https://getmoonshine.app/en/docs/4.x/appearance/colors
Retrieve specific colors by name, optionally specifying the output format (HEX or stored). Also shows how to get a specific shade of a base color.
```php
$colorManager->get('primary'); // Returns HEX by default
$colorManager->get('primary', hex: false); // Returns the stored format
// Get shade
$colorManager->get('base', 500); // Get a specific shade
```
--------------------------------
### Select Field with Asynchronous Initialization
Source: https://getmoonshine.app/en/docs/4.x/fields/select
This example demonstrates how to load asynchronous options immediately when the page loads, rather than waiting for user interaction. Use `asyncOnInit(whenOpen: false)` to fetch data before the select is opened.
```php
use MoonShine\UI\Fields\Select;
Select::make('Country', 'country_id')
->options([
'value 1' => 'Option Label 1',
'value 2' => 'Option Label 2',
])
->async('/search')
->asyncOnInit(whenOpen: false)
```
--------------------------------
### Create Menu with Menu Items
Source: https://getmoonshine.app/en/docs/4.x/components/menu
Initialize a menu component using an array of MenuItem objects. Ensure to import MenuItem and Menu classes.
```php
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\Menu;
Menu::make([
MenuItem::make('/', 'Item')
]);
```
```php
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\Menu;
Menu::make([
MenuItem::make('/', 'Item')
]);
```
```php
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\Menu;
Menu::make([
MenuItem::make('/', 'Item')
]);
```
```php
use MoonShine\MenuManager\MenuItem;
use MoonShine\UI\Components\Layout\Menu;
Menu::make([
MenuItem::make('/', 'Item')
]);
```
--------------------------------
### Get Route Name
Source: https://getmoonshine.app/en/docs/4.x/model-resource/routes
Retrieves a specific route name from the resource.
```php
$resource->getRoute('crud.massDelete');
```
--------------------------------
### PrettyLimit with Enum Colors
Source: https://getmoonshine.app/en/docs/4.x/components/pretty-limit
Demonstrates how to use the PrettyLimit component with predefined Color enum values for background styling.
```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);
```
--------------------------------
### Collapse Basics
Source: https://getmoonshine.app/en/docs/4.x/components/collapse
Demonstrates the basic instantiation of the Collapse component with a label and nested components. The `persist` parameter controls state preservation.
```php
use MoonShine\UI\Components\Collapse;
Collapse::make('Title/Slug', [
Text::make('Title'),
Text::make('Slug'),
])
```
--------------------------------
### Get Logo Path
Source: https://getmoonshine.app/en/docs/4.x/appearance/layout
Define the getLogo method to specify the path to the logo.
```PHP
protected function getLogo(bool $small = false): string { }
```
```PHP
protected function getLogo(bool $small = false): string
{
// ...
}
```
--------------------------------
### ActionButton Method Call with Download
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
Shows how to chain the download() method when the called method returns a file.
```php
ActionButton::make('ZIP')
->method('zip')
->download()
```
--------------------------------
### Test Resource Index Page Success
Source: https://getmoonshine.app/en/docs/4.x/advanced/testing
This example demonstrates how to write a test to verify that the resource's index page returns a successful response.
```php
public function test_index_page_successful(): void
{
$response = $this->get(
$this->getResource()->getIndexPageUrl()
)->assertSuccessful();
}
```
--------------------------------
### Get Home URL
Source: https://getmoonshine.app/en/docs/4.x/appearance/layout
Define the getHomeUrl method to specify the URL of the main page.
```PHP
protected function getHomeUrl(): string { }
```
```PHP
protected function getHomeUrl(): string
{
// ...
}
```
--------------------------------
### Check Active Page Type
Source: https://getmoonshine.app/en/docs/4.x/model-resource/routes
Examples of checking the type of the active page using instanceof.
```php
if($resource->getActivePage() instanceof IndexPage)
if($resource->getActivePage() instanceof FormPage)
if($resource->getActivePage() instanceof DetailPage)
```
--------------------------------
### Create a Basic Link
Source: https://getmoonshine.app/en/docs/4.x/components/link
Use the `Link::make()` method to create a styled link with a specified href and label. This is the fundamental way to instantiate the Link component.
```php
use MoonShine\UI\Components\Link;
Link::make('https://moonshine-laravel.com', 'Moonshine')
```
--------------------------------
### Setting Toggler Attributes
Source: https://getmoonshine.app/en/docs/4.x/components/off-canvas
Example of using togglerAttributes to add a CSS class to the toggler element.
```php
OffCanvas::make('Title', 'Content...', 'Show Panel')
->togglerAttributes([
'class' => 'mt-2'
]),
```
--------------------------------
### Basic Heading Usage
Source: https://getmoonshine.app/en/docs/4.x/components/heading
Demonstrates how to create a basic heading component using the `Heading::make` method. This example creates a heading with level 2.
```php
use MoonShine\UI\Components\Heading;
Heading::make('Title', 2)
```
--------------------------------
### Create MobileBar Instance
Source: https://getmoonshine.app/en/docs/4.x/components/mobilebar
Instantiate the MobileBar component using the `make` method. Accepts an array of components as an argument.
```php
use MoonShine\UI\Components\Layout\MobileBar;
MobileBar::make([
Fragment::make([
Logo::make(
'/',
'/vendor/moonshine/logo-small.svg',
)->minimized(),
])->class('menu-logo'),
Fragment::make([
Divider::make('Mobile bar'),
Menu::make()->top(),
])->class('menu menu--horizontal'),
Fragment::make([
Profile::make(),
Div::make()->class('menu-divider menu-divider--vertical'),
ThemeSwitcher::make(),
Div::make([
Burger::make()->mobileBar(),
])->class('menu-burger'),
])->class('menu-actions'),
]),
```
--------------------------------
### Generate Basic Resource URL
Source: https://getmoonshine.app/en/docs/4.x/model-resource/routes
Use getUrl() to get the URL for the first page of the resource.
```php
$resource->getUrl();
```
--------------------------------
### Retrieve Route from Resource Context
Source: https://getmoonshine.app/en/docs/4.x/advanced/routes
Example of how to retrieve a route name, such as 'permissions', from within the resource context.
```php
$this->getRoute('permissions')
```
--------------------------------
### Get Form Method Signature
Source: https://getmoonshine.app/en/docs/4.x/configuration
The signature for the `getForm` method, used to retrieve a form instance by name.
```php
getForm(
string $name,
string $default,
mixed ...$parameters,
)
```
--------------------------------
### Basic Action Button Initialization
Source: https://getmoonshine.app/en/docs/4.x/components/action-button
Initialize an Action Button with a label and an endpoint. This is the most basic configuration.
```php
ActionButton::make('Button Label', '/endpoint')
```
--------------------------------
### Get Page Method Signature
Source: https://getmoonshine.app/en/docs/4.x/configuration
The signature for the `getPage` method, used to retrieve a page instance by name.
```php
getPage(
string $name,
string $default,
mixed ...$parameters,
)
```
--------------------------------
### Basic Icon Usage
Source: https://getmoonshine.app/en/docs/4.x/appearance/icons
Demonstrates the basic usage of the icon function to display a preset icon by its name.
```php
->icon('cog')
```
--------------------------------
### Create MoonShine Superuser with Options
Source: https://getmoonshine.app/en/docs/4.x/advanced/commands
Creates a superuser with specified username, name, and password. Allows pre-defining user credentials during creation.
```bash
moonshine:user {--u|username=} {--N|name=} {--p|password=}
```
```bash
moonshine:user {--u|username=} {--N|name=} {--p|password=}
```
```bash
moonshine:user {--u|username=} {--N|name=} {--p|password=}
```
```bash
moonshine:user {--u|username=} {--N|name=} {--p|password=}
```
```bash
moonshine:user {--u|username=} {--N|name=} {--p|password=}
```
--------------------------------
### TableBuilder Initialization
Source: https://getmoonshine.app/en/docs/4.x/components/table-builder
Initialize the TableBuilder component with optional fields and items. This is the basic setup for creating a table.
```php
use MoonShine\UI\Components\Table\TableBuilder;
TableBuilder::make(iterable $fields = [], iterable $items = [])
```
--------------------------------
### Create HTML Layout
Source: https://getmoonshine.app/en/docs/4.x/components/html
Instantiate the Html component with Head and Body components.
```php
use MoonShine\UI\Components\Layout\Html;
use MoonShine\UI\Components\Layout\Head;
use MoonShine\UI\Components\Layout\Body;
Html::make([
Head::make([]),
Body::make([]),
]);
```
--------------------------------
### Basic Alert Usage (PHP Class)
Source: https://getmoonshine.app/en/docs/4.x/components/alert
Demonstrates how to create a basic alert using the Alert class. Ensure the MoonShine UI Components namespace is imported.
```php
use MoonShine\UI\Components\Alert;
Alert::make()->content('Text');
```