But, I want to store a user_id for each request. I want to set the user_id in my controller by using Auth::id().
This, however, does not work with the Model::create() method because I excluded the user_id from being fillable.
How to properly get around that issue? Thank you very much!
I handle these situations in a couple ways. I usually add the user_id to the $fillable array, but ensure it always gets overridden either in the controller, or the model's creating() static boot method.
It's ok, you're not really overriding the core, but just hooking into the model events.
For updates, you can similarly use the static updating() method:
Wouldn't this bloat my user-class with a ton of relations (by following this way on every Model)?
Also, could this be a security issue? Connecting the user to every model?
hey, your user model is connected - thats what you asked for..
What if you want to create the model and assign to someone other than the logged in user? With your creating method you are always hijacking the user_id.
@Talinon this is fine for tiny app such as your own blog where you will be the only user and no other user will interact with the site. As soon as you have more than one user, this is bad for the reasons that @Snapey said.
Anyways, to answer the question: The approach I like to take is by not using Model::create, but rather a new instance of the class. That way I have a bit more flexibility and don't have to care about foreign key naming:
$model = new Model($request->only(['field1', 'field2']));
$model->user()->associate($request->user());
// do anything else for the model
$model->save();
@CRNKOVIC - It has nothing to do with the number of users, rather it uses the currently authenticated user; which may be fine, depending on the app. Snapey was stating that it may not be the best solution, IF you have the need to assign it to another user other than the one submitting the request.
There are plenty of ways to go about it.
Another option is to use forceFill() at an explicit end point, which forces the attributes to be mass assigned.