I have a belongsTo field on the selection of which i want to show/hide another field using nova dependency container. But it only allows to give id in the dependsOn('page.id', 1) but i want to show the field on the basis of page status like dependsOn('page.status', 'active').
Is there a way to do this?
My Answer:
Currently, Laravel Nova Dependency Container only allows you to specify the 'id' property of the dependent resource in the dependsOn method. However, you can achieve the desired functionality by using a custom JavaScript script in your Nova resource.
You can create a custom JavaScript script that listens for changes in the 'belongsTo' field and then shows/hides the dependent field based on the selected value. Here's an example of how you can achieve this:
1. Create a custom JavaScript file in your Nova resource directory (e.g., resources/js/nova-dependency.js) and add the following code:
javascript
Nova.booting((Vue, router) => {
Vue.component('dependent-field', {
props: ['value'],
mounted() {
this.toggleDependentField();
},
watch: {
value: function (newValue) {
this.toggleDependentField();
}
},
methods: {
toggleDependentField() {
if (this.value === 'active') {
document.getElementById('dependent-field').style.display = 'block';
} else {
document.getElementById('dependent-field').style.display = 'none';
}
}
}
});
});
2. Include the custom JavaScript file in your Nova resource view file (e.g., resources/views/detail.blade.php) using the following code:
html
3. Add the 'dependent-field' component to your Nova resource view file and pass the value of the 'belongsTo' field to it:
html
4. Update your Nova resource controller to pass the value of the 'belongsTo' field to the view:
php
public function fields(Request $request)
{
return [
BelongsTo::make('Page', 'page_id')->searchable(),
Text::make('Dependent Field')->onlyOnDetail(),
];
}
public function detail(Request $request, $resource)
{
return response()->view('detail', [
'belongsToFieldValue' => $resource->page->status,
]);
}
With this setup, the custom JavaScript script will listen for changes in the 'belongsTo' field and show/hide the dependent field based on the selected value. This way, you can achieve the desired functionality of showing/hiding a field based on the status of the 'belongsTo' field in Laravel Nova.
Rate this post
5 of 5 based on 8240 votesComments