To address the issue of dependent dropdowns not displaying the old record correctly, you need to ensure that the default values for both the parent and child categories are set correctly when the form is loaded. Additionally, you need to make sure that the relationships are properly defined and that the form fields are correctly populated with the existing data.
Here's a revised version of your code with some adjustments to ensure that the old records are displayed correctly:
Select::make('category_id')
->options(Tag::type(12)
->whereNull('parent_id')
->pluck('tag', 'id'))
->default(function ($record) {
// Get the current category of the article
$category = $record->categories()->first();
// If the category exists and has a parent, return the parent's id
if ($category && $category->parent) {
return $category->parent->id;
}
// Otherwise, return null
return null;
})
->live()
->label('Parent Category'),
Select::make('subcategory_id')
->label('Child Category')
->relationship('categories', 'tag', modifyQueryUsing: function (Builder $query, Forms\Get $get) {
return $query->where('parent_id', $get('category_id'))->orderBy('id');
})
->default(function ($record) {
// Get the current category of the article
$category = $record->categories()->first();
// If the category exists, return its id
if ($category) {
return $category->id;
}
// Otherwise, return null
return null;
}),
Additionally, ensure that your categories relationship is correctly defined in your model:
public function categories()
{
return $this->morphToMany(Tag::class, 'taggable')
->where('tag_type', 12)
->withTimestamps();
}
And make sure that the Tag model has the necessary relationships to get the parent category:
class Tag extends Model
{
public function parent()
{
return $this->belongsTo(Tag::class, 'parent_id');
}
public function children()
{
return $this->hasMany(Tag::class, 'parent_id');
}
}
By ensuring that the default values are correctly set and that the relationships are properly defined, the dependent dropdowns should display the old records correctly when you refresh or return to edit the article.