在资源文件中使用此代码
@forelse($teachers as $teacher)
{{$teacher->name}} {{$teacher->subjects}}<br>
@empty
Nothing
@endforelse
获得此值
helooo [{"id":3,"name":"Hindi","created_at":"2017-11-18 12:43:33","updated_at":"2017-11-18 12:43:33","pivot":{"teacher_id":16,"subject_id":3}}]
malik [{"id":2,"name":"English","created_at":"2017-11-18 12:43:12","updated_at":"2017-11-18 12:43:12","pivot":{"teacher_id":17,"subject_id":2}}]
hello [{"id":1,"name":"Maths","created_at":"2017-11-18 12:42:34","updated_at":"2017-11-18 12:42:34","pivot":{"teacher_id":18,"subject_id":1}}]
但是使用了
{{$teacher->name}} {{$teacher->subjects->name}}
收到错误
Property [name] does not exist on this collection instance
如何才能获得laravel中的名称值
答案 0 :(得分:1)
由于它有很多,所以你需要迭代每位老师的主题:
@forelse($teachers as $teacher)
{{ $teacher->name }}<br>
@foreach ($teacher->subjects as $subject)
{{ $subject->name }}<br>
@endforeach
@empty
Nothing
@endforelse
答案 1 :(得分:0)
看起来返回的数据是数组中的对象。尝试添加零以选择此arr中的第一个obj。像这样:
$teacher->subjects[0]->name
祝你好运!