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);
}
There is a user_id column on the articles table,
This is my store function but when I create the post I am looking for a way to store the logged in user id to the user_id column in the articles table.
Get the auth
ed user.
$article->user_id = Auth::user()->id;
$article->save();
Simple
$article->user_id = Auth::user()->id;
It will store the authenticated user id in the user_id
field of your article table.
In your case change your Store code to
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);
}
But there is another method without using even the name space and all.
You can just fix this with the following code:
$article->user_id = auth()->user()->id;
instead of:
$article->user_id = Auth::user()->id;