将用户名关联到他们创建的 post

Accociate a user name to the post they created

如果我创建了一个博客 post,我怎样才能将我的名字与它相关联?例如,在列出所有博客 post 的页面上,我将看到他们创建的 post 的用户名。是吗?

在我的 post 控制器中:

public function __construct(Post $post, User $user)
 {
    $this->middleware('auth',['except'=>['index','show',]]);
    $this->post = $post;
    $this->user = $user;
 }

public function show($id)
 {
    $user = $this->user->first(); // This seems to show the first user
    $post = $this->post->where('id', $id)->first(); // Grabs the assigned post
 }

在我的 show.blade.php:

{{ $user->name }}

如何显示创建 post 的用户的姓名?我认为这个 $user = $this->user->first(); 会起作用。我是 Laravel 的新手,我正在使用 Laravel 5。

谢谢!

编辑 用户模型:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, BillableContract {

use Authenticatable, CanResetPassword;

use Billable;


/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';


/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email', 'password', 'company_url', 'tagline','company_name', 'company_description'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

/**
 * @var array
 *
 */

protected $dates = ['trial_ends_at', 'subscription_ends_at'];


  public function posts()
  {
    return $this->hasMany('App\Post')->latest()->where('content_removed', 0);


  }


}

Post 型号:

class Post extends Model {

/**
 * Fillable fields for a new Job.
 * @var array
 */

protected $fillable = [
    'post_title',
    'post_description',
    'post_role',
    'post_types',
    'post_city',
    'post_country',
    'template',
    'content_removed',

];

public function users()
{
    return $this->hasMany('App\User')->orderBy('created_at', 'DESC');
}


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



}

首先 您需要将以下行添加到您的 post 模型

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

然后在你展示方法

public function show($id)
{
    $post = $this->post->with('creator')->findOrFail($id);
    return view('show',compact('post'));
}

在你身上show.blade.php

{{ $post->creator->name }}