如何解决如何在Laravel中检索和显示雄辩的关系 我要完成的工作:我收到的错误:我一直在尝试的东西:
我要完成的工作:
检索与已验证用户相关的所有App\Post
模型,并将其显示在视图中。
我收到的错误:
Undefined variable:
和Property [id] does not exist on this collection instance
,点击<a name="posts">
标签。
我一直在尝试的东西:
PagesController :
public function show($id) {
$user = User::find($id);
return view('pages.index',compact('user'));
}
索引:
@extends('layouts.app')
@section('content')
<h1>Welcome to notesite!</h1>
<a href="/notes/show/{{ Auth::user()->id }}" name="posts">Show your posts</a>
@endsection
路线:
Route::get('/',function () {
return view('welcome');
});
Route::get('/pages/index','PagesController@index');
Route::get('/pages/about','PagesController@about');
Route::get('/pages/services','PagesController@services');
Route::get('/notes/index','NotesController@index');
Route::get('/notes/show/{user}','NotesController@show');
Auth::routes();
Route::get('/home','HomeController@index')->name('home');
任何人都可以提供解决方案吗?
解决方法
欢迎您!
如果您打算处理大量记录,建议您阅读Eloquent relationships,尤其是有关eager loading的部分。
您可以执行以下操作:
用户模型
// Add this bit to your existing model to define the relationship
// ( assuming that 1 user can have many different posts )
public function posts() {
return $this->hasMany('App\Post');
}
发布模型
// By default,Eloquent will automatically determine the proper foreign key column,// noted here as user_id
protected $fillable = ['title','body','user_id'];
PostController
public function show() {
$posts = App\User::find(Auth::id())->posts; // Fetch the authenticated users posts
return view('show-posts',compact('posts') ); // Pass them back to the view
}
routes / web.php
Route::view('/pages/index','index');
Route::get('/posts/show','PostController@show');
index.blade.php
<a href="/posts/show">Show user-specific posts!</a>
show-posts.blade.php
@foreach( $posts as $post )
{{ $post->body }}
@endforeach
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。