I am trying to loop through a related model to my Users table call AdminNotes using a foreach in my blade view. However, I am getting the following error. Any ideas?
Trying to get property of non-object (View: /home/vagrant/Code/sass_l5/resources/views/users/edit.blade.php)
at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/home/vagrant/Code/sass_l5/storage/framework/views/5da731c9bf1a02452259c329d3c273e0', '226', array('__path' => '/home/vagrant/Code/sass_l5/storage/framework/views/5da731c9bf1a02452259c329d3c273e0', '__data' => array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User)), 'obLevel' => '1', '__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'user' => object(User), 'note' => true)) in 5da731c9bf1a02452259c329d3c273e0 line 226
I have the relationships set up like this:
User Model:
...
class User extends Model
{
...
public function adminNotes()
{
return $this->hasOne('sass\AdminNote');
}
...
}
AdminNote Model:
...
class AdminNote extends Model {
...
public function user()
{
return $this->belongsTo('sass\User');
}
...
}
edit.blade.php
...
@if (count($user->adminNotes) >= 1)
@foreach ($user->adminNotes as $note)
{{ $note->created_at }}
{{ $note->notes }}
@endforeach
@else
...
dd($user->adminNotes):
AdminNote {#274 ▼
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:5 [▼
"id" => 25
"user_id" => 1
"notes" => "Test note"
"created_by" => 1
"created_at" => "2014-01-01 00:00:00"
]
#original: array:5 [▼
"id" => 25
"user_id" => 1
"notes" => "Test note"
"created_by" => 1
"created_at" => "2014-01-01 00:00:00"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
dd($note)
true
Thanks to Ross Wilson for pointing out that my relationships were set up to only have one note, where in they needed to be set up to have many notes.
...
class User extends Model
{
...
public function adminNotes()
{
return $this->hasMany('sass\AdminNote');
}
...
}