Basics
In CrudResource
(ModelResource
) on the formPage
, FormBuilder
is used, so we recommend that you also check out the FormBuilder section of the documentation.
Validation
Validation is as simple as in FormRequests
classes from Laravel
.
Just add the rules in the rules()
method of the model resource in the usual way.
namespace App\MoonShine\Resources; use App\Models\Post;use MoonShine\UI\Fields\Text;use MoonShine\Laravel\Resources\ModelResource; class PostResource extends ModelResource{ protected string $model = Post::class; protected string $title = 'Posts'; //... protected function rules(mixed $item): array { return [ 'title' => ['required', 'string', 'min:5'] ]; } //...}
Messages
Using the validationMessages()
method, you can create your own validation error messages.
class PostResource extends ModelResource{ protected string $model = Post::class; protected string $title = 'Posts'; //... public function validationMessages(): array { return [ 'email.required' => 'Email is required' ]; } //...}
Preparing Input Data for Validation
If you need to prepare or clean any data from the request before applying validation rules, you can use the prepareForValidation()
method.
class PostResource extends ModelResource{ protected string $model = Post::class; protected string $title = 'Posts'; //... public function prepareForValidation(): void { moonshineRequest()?->merge([ 'email' => request() ?->string('email') ->lower() ->value() ]); } //...}
Displaying Errors
By default, validation errors are displayed at the top of the form.
The $errorsAbove
property is used to control the display of validation errors at the top of the form.
Relevant only if "Asynchronous Mode" is turned off
class PostResource extends ModelResource{ // .. protected bool $errorsAbove = true; // ..}
Precognition
If it is necessary to perform precognition
validation in advance, you need the precognitive()
method.
Details in the Laravel documentation
class PostResource extends ModelResource{ // ... protected bool $isPrecognitive = true; // ...}
Buttons
To add buttons, use ActionButton
and the formButtons
method in the resource.
More about ActionButton
protected function formButtons(): ListOf{ return parent::formButtons()->add(ActionButton::make('Link', '/endpoint'));}
Asynchronous Mode
By default, "Asynchronous Mode" is enabled in ModelResource
, but if you need to turn it off, set the $isAsync
property to false.
class PostResource extends ModelResource{ // ... protected bool $isAsync = false; // ...}
Modifiers
Components
You can fully replace or modify the resource's FormBuilder
for the edit page. To do this, use the modifyFormComponent
method.
public function modifyFormComponent(ComponentContract $component): ComponentContract{ return parent::modifyFormComponent($component)->customAttributes([ 'data-my-attr' => 'value' ]);}