Laravel Nova’s dependson
attribute allows you to dynamically show or hide fields based on the value of another field. It provides a way to create conditional fields in your Nova resources.
Let’s say we have a resource to manage products, and we want to show additional fields based on the product type. For example, if the product type is “Electronic”, we want to show fields for specifications such as screen size, memory, and processor. If the product type is “Clothing”, we want to show fields for size, color, and fabric.
To achieve this, we can define the fields and their dependencies in the resource’s fields
method. Here’s an example:
namespace App\Nova;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Text;
class ProductResource extends Resource
{
public function fields(Request $request)
{
return [
Select::make('Product Type')->options([
'Electronic' => 'Electronic',
'Clothing' => 'Clothing',
]),
Text::make('Screen Size')->dependsOn('Product Type', 'Electronic'),
Text::make('Memory')->dependsOn('Product Type', 'Electronic'),
Text::make('Processor')->dependsOn('Product Type', 'Electronic'),
Text::make('Size')->dependsOn('Product Type', 'Clothing'),
Text::make('Color')->dependsOn('Product Type', 'Clothing'),
Text::make('Fabric')->dependsOn('Product Type', 'Clothing'),
];
}
}
In this example, we have a Select
field to choose the product type, and other fields that depend on the selected value of the product type. The dependsOn
method is used to define the field’s dependency.
When the product type is “Electronic”, the fields for screen size, memory, and processor will be displayed. When the product type is “Clothing”, the fields for size, color, and fabric will be displayed.
The dependsOn
method takes two arguments: the field name to depend on, and the value that triggers the display of the field. In our example, the field name is “Product Type” and the values triggering the display are “Electronic” and “Clothing”.
Make sure to import the required classes at the top of your resource file. Additionally, you may need to include the necessary JavaScript files for Laravel Nova to handle the conditional field display properly.