This is a package to integrate a dependent filter with Laravel Nova version 4.
Require this package with composer.
composer require resham/nova-dependent-filter
Once the Installation is complete, you can use it by creating a filter class.
use Resham\NovaDependentFilter\DependentFilter;
class CountryFilter extends DependentFilter
{
/**
* Name of filter.
*
* @var string
*/
public $name = 'Country';
/**
* The filter's attribute. Also, it is key of filter.
*
* @var string
*/
public $key = 'country_code';
/**
* Get the filter's available options.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param array $filters
* @return array
*/
public function options(NovaRequest $request, array $filters = [])
{
return Country::pluck('name', 'country_code');
}
}
Let's have a dependent filter state that depends on the country, we can achieve the dynamic-dependent filter
Define the parent filter(on which other filters depend)
use Resham\NovaDependentFilter\DependentFilter;
class CountryFilter extends DependentFilter
{
/**
* Name of filter.
*
* @var string
*/
public $name = 'Country';
/**
* The filter's attribute. Also, it is key of filter.
*
* @var string
*/
public $key = 'country_code';
/**
* The other filters key whose are depends on this filter.
*
* @var string[]
*/
public $parentOf = ['state'];
/**
* Get the filter's available options.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param array $filters
* @return array
*/
public function options(NovaRequest $request, array $filters = [])
{
return Country::pluck('name', 'country_code');
}
}
Note: Don't forget to define the key of the child filter on the
$parentOf
property.
Let's define the child filter which is depends on parent filter.
use Resham\NovaDependentFilter\DependentFilter;
class StateFilter extends DependentFilter
{
/**
* Name of filter.
*
* @var string
*/
public $name = 'State';
/**
* The filter's attribute. Also, it is key of filter.
*
* @var string
*/
public $key = 'state';
/**
* Get the filter's available options.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param array $filters
* @return array
*/
public function options(NovaRequest $request, array $filters = [])
{
return State::where('country_code', $filters['country_code'] ?? '')
->pluck('name', 'id');
}
}
We can register the filter as we define with nova.
/**
* Get the filters available for the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function filters(NovaRequest $request)
{
return [
new CountryFilter
];
}
Also, you can use CountryFilter::make()
/**
* Get the filters available for the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array
*/
public function filters(NovaRequest $request)
{
return [
CountryFilter::make()
];
}
If you discover any issues, please email at reshampokhrel57@gmail.com.