Or in the controller
public function store() {
$data = Request::all();
$data['created_by'] = Auth::user()->id;
Article::create($data);
...
Hello everyone,
When creating a new record, where should I be setting the created_by user's ID? I know it should obviously not be accessible via the form, but should I be setting that value in the controller or in the model?
This is probably not the correct way? In my model:
public function setCreatedByAttribute(){
$this->attributes['created_by'] = Auth::user()->id;
}
Hey! You could do that directly in your controller, like this, using a simple hasMany relation:
php
//In your user model:
public function articles()
{
return $this->hasMany('App\Article');
}
Then you can easily create an article using this:
//In your user model:
public function create()
{
Auth::user()->articles()->create($article);
}
Like this, the user field will automatically be used. And you should call it 'user_id' in your articles table.
Jeffrey Way explains that very well in the last Laravel 5 videos, you should give them a look :)
Please or to participate in this conversation.