Model 1: Walks
return $this->belongsTo('App\Models\Device','device_uuid','device_uuid');
}
Model 2: Device
public function walks() {
return $this->hasMany('App\Models\Walks','device_uuid','device_uuid');
}
In my index file:
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Walk Date</th>
<th>Device Name</th>
<th>In</th>
<th>Out</th>
<th width="280px">Action</th>
</tr>
@foreach ($walks as $walk)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $walk->walk_datetime }}</td>
<td>{{ $walk->device->device_uuid }}</td> <========
<td>{{ $walk->walk_in }}</td>
<td>{{ $walk->walk_out }}</td>
<td>
<form action="{{ route('walks.destroy',$walk->id) }}" method="POST">
<a class="btn btn-primary" href="{{ route('walks.edit',$walk->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
this causes errors:
<td>{{ $walk->device->device_uuid }}</td> <========
"Trying to get property 'device_uuid' of non-object"
If I do this:
<td>{{ $walk->device }}</td>
I get:
{"id":1,"device_uuid":"1902101300368","device_name":"Test 1","created_at":null,"updated_at":null}
which means the relation works correct.
Is there any other way that I should use to access the "device_mame" attribute?
Related to questions below.. All walks has a valid device linked.
:) It seems to me that some Walks
don't have a Device
. That's why it (usually) throws that error.
Similar problem on Laracasts.
Or what you can do is use ternary operators
<td>{{(isset($walk->device->device_uuid)? $walk->device->device_uuid : ''}}</td>