I need to select the id and name field, pass the collection to the view and iterate over it to generate options for a select. However, I am getting the following error:
Trying to get property of non-object (View: ../resources/views/layouts/app.blade.php) (View: ../resources/views/layouts/app.blade.php)
Controller
public function index()
{
$propertyTypes = PropertyType::pluck('name', 'id');
return view('home', compact('propertyTypes'));
}
View
@foreach($propertyTypes as $propertyType)
<option value="{{ $propertyType->id }}">
{{ $propertyType->name }}
</option>
@endforeach
Table
ID Name
1 Detached
2 Semi-detached
3 Terraced
4 Flat
5 Bungalow
6 Land
7 Park Home
You're using the pluck
method to get the results as key-value
pair but in your view you're trying to access the value as an object which is causing this error.
Either you've to fetch your results as models or you've to update your view.
Option 1: Fetch results as models
public function index()
{
$propertyTypes = PropertyType::select('name', 'id')->get();
return view('home', compact('propertyTypes'));
}
Option 2: Iterate over collection as key-value
@foreach($propertyTypes as $id => $name)
<option value="{{ $id }}">
{{ $name }}
</option>
@endforeach
Try just:
public function index()
{
$propertyTypes = PropertyType::pluck('name', 'id');
return view('home', ['propertyTypes' => $propertyTypes]);
}
If not work You have to check your view
for example:
views/ControllerName/blog/index.blade.php
Exists this blade
or Not?
Because your stack trace
wrote in resources/views/layouts/app.blade.php
Try this.
This will give you the required collection to iterate through.
public function index()
{
$propertyTypes = PropertyType::select('name', 'id')->get();
return view('home', compact('propertyTypes'));
}
View
@foreach($propertyTypes as $id => $name)
<option value="{{ $id }}">
{{ $name }}
</option>
@endforeach
now why we need to do like this. if you print your object dd($propertyTypes->tooArray()); like this you will see an array containing id column value as array index. so to get this value you need to store the index value somewhere, during foreach I use $id => $name so the $id will get index value and $name will get data of that index which is name column value