public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255|min:2',
'slug' => 'required|alpha_dash|unique:articles,slug',
'category_id' => 'required|integer',
'content' => 'required|min:2'
));
$article = new Article;
$article->title = $request->title;
$article->slug = $request->slug;
$article->category_id = $request->category_id;
$article->content = $request->content;
$article->save();
Session::flash('success', 'Your article has been published.');
return redirect()->route('article.show', $article->id);
}
文章表上有一个user_id列,
这是我的商店功能,但是当我创建帖子时,我正在寻找一种方法将登录的用户ID存储到文章表格中的user_id列。
答案 0 :(得分:2)
获取auth
ed用户。
$article->user_id = Auth::user()->id;
$article->save();
答案 1 :(得分:2)
简单
$article->user_id = Auth::user()->id;
它会将经过身份验证的用户ID存储在文章表的user_id
字段中。
在您的情况下,将商店代码更改为
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255|min:2',
'slug' => 'required|alpha_dash|unique:articles,slug',
'category_id' => 'required|integer',
'content' => 'required|min:2'
));
$article = new Article;
$article->title = $request->title;
$article->slug = $request->slug;
$article->category_id = $request->category_id;
//it will store the current logged in user id in user_id field
$article->user_id = Auth::user()->id;
$article->content = $request->content;
$article->save();
Session::flash('success', 'Your article has been published.');
return redirect()->route('article.show', $article->id);
}
答案 2 :(得分:1)
但是还有另一种方法,甚至不使用名称空间和全部。
您可以使用以下代码解决此问题:
$article->user_id = auth()->user()->id;
代替:
$article->user_id = Auth::user()->id;