Here's an example of how you might structure a Blade component for a category dropdown that can be used for both storing and updating categories:
@props(['categories', 'selectedId' => null])
<select class="form-select form-select-solid" name="parent_id"
data-control="select2" data-placeholder="Select an option"
data-allow-clear="true">
<option></option>
@foreach ($categories as $category)
<option value="{{ $category->id }}" @selected($category->id == $selectedId)>
{{ str_repeat('-', $category->depth) }} {{ $category->name }}
</option>
@endforeach
</select>
{{-- Create Form --}}
<x-category-dropdown :categories="$topLevelCategories" />
{{-- Edit Form --}}
<x-category-dropdown :categories="$topLevelCategories" :selectedId="$currentCategory->parent_id" />
public function create()
{
$topLevelCategories = Category::whereNull('parent_id')->get();
return view('categories.create', compact('topLevelCategories'));
}
public function edit(Category $category)
{
$topLevelCategories = Category::whereNull('parent_id')
->where('id', '!=', $category->id)
->get();
return view('categories.edit', compact('category', 'topLevelCategories'));
}
// app/View/Components/CategoryDropdown.php
namespace App\View\Components;
use Illuminate\View\Component;
use App\Models\Category;
class CategoryDropdown extends Component
{
public $categories;
public $selectedId;
/**
* Create a new component instance.
*
* @param Collection $categories
* @param int|null $selectedId
*/
public function __construct($categories, $selectedId = null)
{
$this->categories = $categories;
$this->selectedId = $selectedId;
}
/**
* Get the view / contents that represent the component.
*
* @return \Illuminate\View\View|string
*/
public function render()
{
return view('components.category-dropdown');
}
}