skip to Main Content

I’m trying to populate a HTML select dropdown with values of a particular column in the database which is an array in this format ["Red","Yellow","Blue"].

I know how to pull the entire product instance for a particular row from DB as a collection and pass it to the view from the controller using;

public function index(){
   $product = Product::where('id','=','12')->get();
   return view('product_details', compact('product'));
}

Now, for the row I have accessed, I want to populate a select dropdown with the value of the colours column for the row with the id of 12 which is ["Red","Yellow","Blue"] which is in the products table in the database. I have no clue on how to achieve that. Please help out.

2

Answers


  1. Controller

    public function index()
    {
       $product = Product::findOrFail(12); // Assuming the ID is 12
       $colors = $product->colors; // Assuming the array column is named "colors"
    
       return view('product_details', compact('colors'));
    }
    

    Dropdown

    <select name="color">
       @foreach ($colors as $color)
           <option value="{{ $color }}">{{ $color }}</option>
       @endforeach
    </select>
    
    Login or Signup to reply.
  2. From all discussion on comments I believe you are unfamiliar with a few concepts of Laravel, its models and blade files. I’ll try going through them with you.

    The Blade File

    I like Karl Hill’s approach to mapping the colors on the blade file. It did not work because we assumed that you had an array of strings, when you actually have a raw string value representing an array. This is an "issue" with the model, so we’ll keep assuming that and fix it, so the current solution should work:

    <select name="color">
        @foreach ($colors as $color)
            <option value="{{ $color }}">{{ $color }}</option>
        @endforeach
    </select>
    

    Another option would be forwarding the whole $product to the view, then it would look like this:

    <select name="color">
        @foreach ($product->colors as $color)
            <option value="{{ $color }}">{{ $color }}</option>
        @endforeach
    </select>
    

    The Controller

    You also had an issue with finding your model using the find() method – this is also an issue with the Model, so we’ll stick to it, as it is the best practice on Laravel. Refactoring "bad" or non-standard code is always better than "working around" issues.

    public function index()
    {
        // Product PK will be set to 'id' and the code below **must** work
        $product = Product::findOrFail(12);
    
        // Colors attribute will be: Array("Red", "Yellow", "Blue")
        $colors = $product->colors;
    
        // Modern Laravel has a more sophisticated parameter passage functionality.
        // See https://laravel.com/docs/10.x/blade#passing-data-to-components
        return view('product_details', [
            'colors' => $colors,
        ]);
    }
    

    The Model

    The main issue seem to be here. In order to use find as we stated I need model’s default configurations to be true. If find(12) does not work with this configurations but where('id', '=', 12) does, something wrong and you should debug it until spotting the issue.

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';
    
    /**
     * The "type" of the primary key ID.
     *
     * @var string
     */
    protected $keyType = 'int';
    

    In order for our colors attribute to be properly interpreted as an array, we need to explicitly state it to our model:

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'colors' => 'array',
    ];
    

    The Migration

    Last but not least, we are expecting your table to be somewhat canonical. So here is a minimalistic migration for our model to work as expected, if your migration has peculiarities, they should be well understood:

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('models', function (Blueprint $table) {
            $table->id()->primary();
            // or: $table->integer('id')->primary();
            $table->array('colors');
            // or: $table->jsonb('colors');
            $table->timestamps();
        });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search