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
Controller
Dropdown
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:
Another option would be forwarding the whole
$product
to the view, then it would look like this: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.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. Iffind(12)
does not work with this configurations butwhere('id', '=', 12)
does, something wrong and you should debug it until spotting the issue.In order for our
colors
attribute to be properly interpreted as an array, we need to explicitly state it to our model: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: