将用户名与他们创建的帖子相关联


Accociate a user name to the post they created

如果我创建了一篇博客文章,如何将我的名字与之关联?例如,在一个列出所有博客文章的页面上,我会看到他们创建的帖子的用户名。对

在我的帖子控制器:

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 }}

如何显示创建帖子的用户的姓名?我以为这个$user = $this->user->first();会起作用。我是拉拉威尔的新手,我正在使用拉拉威尔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);

  }

}

后模型:

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');
 }

}

第一个你需要在你的后模型中添加以下行

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'));
}

在您展示的.blade.php 中

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