I am querying a list of staffs from 'itemregistration' table with the eloquent relationship with 'section' table. But I cannot display the information from section table to the view blade.
My controller get the query as follows:
$itemregistrations = Itemregistration::with('section')->get();
When I check the array with:
dd($itemregistrations->toArray());
I get this result:
0 => array:133 [▼
"ItemRegistrationID" => 1
"RegistrationDate" => "2005-12-01"
"SectionID" => 12
"name" => "A SANTESH"
"section" => array:2 [ …2]
]
The section array should contain 'SectionID' and 'sectionname' fields.
If I check with dd($itemregistration);
it produce
Collection {#1948 ▼
#items: array:1125 [▼
0 => Itemregistration {#1990 ▼
#primaryKey: "ItemRegistrationID"
#hidden: array:1 [ …1]
+timestamps: false
#connection: "mysql"
#table: null
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:133 [ …133]
#original: array:133 [ …133]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [ …1]
#touches: []
#visible: []
#fillable: []
#guarded: array:1 [ …1]
I want to display the result in the blade but failed to fetch the section array value:
@foreach($itemregistrations as $index => $value)
<td>{{ $value->name }}</td>
<td>{{ $value->section->sectionname }}</td>
@endforeach
I also tried:
@foreach($itemregistrations as $index => $value)
<td>{{ $value->name }}</td>
@foreach($value as $section => $val)
<td>{{ $val->sectionname }}</td>
@endforeach
@endforeach
But also failed. The error appears is "Trying to get property of non-object".
I tried to see the values contained in the collection through this code:
@foreach ($itemregistrations as $item)
<tr>
<td>{{ $item }}</td>
<td>{{ $item->section }}</td>
</tr>
@endforeach
And it shows this value in this format:
{"ItemRegistrationID":1,"name":"A Santesh"{"SectionID":12,"sectionname":"E"}}
If I show the result with this:
@foreach ($itemregistrations as $item)
{{ $item->name }}
@endforeach
I can get the name list but to get the sectionname with this
@foreach ($itemregistrations as $item)
<tr>
<td>{{ $item->section->sectionname }}</td>
</tr>
@endforeach
It shows error "Trying to get property of non-object ". I dont understand why I can't get the section values.
My section model:
class Section extends Authenticatable
{
protected $table = 'sections';
protected $primaryKey = 'SectionID';
/**
* Get the user that have agama.
*/
public function itemregistrations()
{
return $this->hasMany('App\Itemregistration', 'SectionID', 'ItemregistrationID');
}
}
Itemregistration model:
class Itemregistration extends Model
{
protected $primaryKey = 'ItemRegistrationID';
/*
* Get all of the owning models.
*/
public function section()
{
return $this->belongsTo('App\Section', 'SectionID');
}
How to get display the query with section array values?