I have a question to ask
So I was trying to create a dropdownlist which will show data from another table. In my controller I declare those table in my create function
public function create()
{
$tenants = Tenant::pluck('name','id');
$categories = Category::pluck('name','id');
return view('items.create', ['categories' => $categories, 'tenants' => $tenants]);
}
and in my views:
<div class='form-group'>
<label for="category_id" class="col-md-4 control-label">Item Category</label>
<div class="col-md-6">
<select class="form-control" name="category" id="categories">
@foreach($categories as $category)
{
<option value={{ $category->id }}>{{ $category->name }}</option>
}
@endforeach
</select>
</div>
</div>
<div class='form-group'>
<label for="tenant_id" class="col-md-4 control-label">Tenant</label>
<div class="col-md-6">
<select class="form-control" name="tenant" id="tenants">
@foreach($tenants as $tenant)
{
<option value={{ $tenant->id }}>{{ $tenant->name }}</option>
}
@endforeach
</select>
</div>
</div>
And it yields an error: Trying to get property of non-object
but if I change pluck to all as i did here:
public function create()
{
$tenants = Tenant::all();
$categories = Category::all();
return view('items.create', ['categories' => $categories, 'tenants' => $tenants]);
}
its working. the problem is I only want to get the value of 'name' & 'id' and with all, it'll also returns the property that i dont need. how can i achieve that with pluck? and if i read the documentation, it says that pluck will retrieve all of the values for a given key but why does my pluck doesn't work? I'm new with php and laravel so any given guide will be so awesome.
When using pluck()
you get the data in [id => 'name']
format, so do this:
@foreach($categories as $id => $category)
<option value={{ $id }}>{{ $category }}</option>
@endforeach
And do the same with $tenants