Wed 24 May 2023
By Vanita saini
category component class code:<?phpnamespace App\View\Components;use Closure;use App\Models\Category;use Illuminate\View\Component;use Illuminate\Contracts\View\View;class Categories extends Component{ /** * Create a new component instance. */ public $categories; public $selected; public $depth; public function __construct($categories, $selected=null, $depth=null,) { $this->categories = $categories; $this->depth = $depth; $this->selected = $selected; } public function buildSelectOptions($categories, $selected='', $depth = 0,) { // Generate HTML for current category $options = ""; foreach ($categories as $category) { $options .= "<option selected( old('name', $selected) == '".$category['id']."') value='".$category['id']."'>".str_repeat('- ', $depth).$category['name']."</option>"; if ($category->children) { $options .= self::buildSelectOptions($category->children,$selected, $depth + 1); } } return $options; } /** * Get the view / contents that represent the component. */ public function render(): View|Closure|string { return view('components.categories'); }}Category Blade file:{!! $buildSelectOptions($categories) !!} Edit Blade File:<div class="row mb-3"> <div class="col"> <label for="parent_id">Parent Category</label> <span class="star-color">*</span> <select class="form-control" id="parent_id" name="parent_id" required> <option value="">Select a Parent Category</option> <option value="0" selected><b>Root</b></option> <x-categories :categories="$categories" :selected="$category->id" /> </select> </div> </div>Controller Class:public function edit(string $id) { $category = Category::find($id); $categories = Category::where('parent_id', '=', 0)->get(); $categoryOptions = Category::buildCategoryOptions($categories); if(!$category){ abort(404); } return view('auth.categories.edit', ['category'=>$category, 'categories'=>$categories, 'categoryOptions'=>$categoryOptions]); }