在laravel中显示用户的帖子

时间:2018-02-03 21:29:49

标签: php laravel web

我是laravel的新手我希望在视图上显示所有帖子,其中包含创建帖子的用户的名字..我试图这样做,但我得到的错误是"试图获取财产'名称'非对象" .. 任何形式的帮助将不胜感激谢谢

user.php的

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

     public function Posts(){
        return $this->hasMany('\App\Post'); 
     }
    protected $fillable = [
        'name', 'email', 'password','verifyToken','dob',
    ];

post.php中

class Post extends Model
{

    public function Users(){
    return $this->belongsTo('\App\User');   
    }
    protected $fillable = [

     'title','body','thumbnail','user_id',

    ];

PostController.php

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       $posts=Post::paginate(5);
       return view('\home2',compact('posts'));


}

web.php

Route::get('/home2', 'PostController@index')->name('home');

Home2.blade.php

@foreach($posts as $post)
<div class="text-center">
<h1 align="center">{{$post->title }}</h1>
<h4 align="center">{{$post->body}}</h4>
<p>{{ $post->created_at->diffForHumans() }}</p>
<p> {{$post->Users->name}}</p>

2 个答案:

答案 0 :(得分:1)

Eager加载用户:

<p> {{$post->user->name}}</p>

然后在刀片上:

public function Posts(){
        return $this->hasMany('\App\Post'); 
}

更新你的关系类 从:

public function posts(){
        return $this->hasMany(Post::class); 
}

use App\Post;

导入顶部 public function user(){ return $this->belongsTo(User::class); }

use App\User;

导入顶部MySQLi

答案 1 :(得分:1)

你的模特应该是这样的。

user.php的

public function posts(){
    return $this->hasMany('App\Post');
}

post.php中

public function user(){
    return $this->belongsTo('App\User','user_id');
}

然后您的刀片代码应该是这样的,

<p> {{$post->user->name}}</p>