Debug School

rakesh kumar
rakesh kumar

Posted on

How to populate a dropdown with data from the database in Laravel, while editing a product category

Certainly! Here's an example of how to populate a dropdown with data from the database in Laravel, while editing a product category:

In controller

namespace App\Http\Controllers;

use App\Models\ProductCategory;

class ProductCategoryController extends Controller
{
    public function edit($id)
    {
        $productCategory = ProductCategory::findOrFail($id);
        $allProductCategories = ProductCategory::all();

        return view('product-categories.edit', compact('productCategory', 'allProductCategories'));
    }

    public function update(Request $request, $id)
    {
        // Handle the update logic here
    }
}
Enter fullscreen mode Exit fullscreen mode

In Blade File

<form action="{{ route('product-categories.update', $productCategory->id) }}" method="POST">
    @csrf
    @method('PUT')

    <label for="name">Category Name:</label>
    <input type="text" id="name" name="name" value="{{ $productCategory->name }}">

    <label for="parent_id">Parent Category:</label>
    <select id="parent_id" name="parent_id">
        <option value="">Select Parent Category</option>
        @foreach($allProductCategories as $category)
            <option value="{{ $category->id }}" @if($category->id == $productCategory->parent_id) selected @endif>
                {{ $category->name }}
            </option>
        @endforeach
    </select>

    <button type="submit">Update</button>
</form>
Enter fullscreen mode Exit fullscreen mode

===========================OR======================

<div class="col-md-4">
                                <label for="user_item_featured" class="text-black">Broker</label>
                                <select  class="selectpicker form-control @error('broker_id') is-invalid @enderror" id="myDropdown" name="broker_id">
                                <option value="">Select a broker</option>
                                @foreach ($broker as $company)
                                <option value="{{ $company->id }}"@if($company->id == $item->broker_id) selected @endif>{{ $company->broker_name  }}</option>
                                @endforeach
                                   </select>                                                                       
                                </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)