Which ones better when storing data? Laravel Hi guys i'm a complete beginner in laravel and i'm a bit confused when using relationships. Can you tell me which one is better when storing a comment on a post with the logged in user id?
1.
$data = request()->validate([
'comment' => 'required',
'post_id' => 'required'
]);
$comment = auth()->user()->comments()->create($data);
or this one:
$data = request()->validate([
'comment' => 'required',
]);
$data['user_id'] = auth()->user()->id;
$comment = $post->comments()->create($data);
They do the same thing but i just wanna know which one is better. Thanks in advance!!
This one
$data = request()->validate([
'comment' => 'required'
]);
$comment = $post->comments()->create($data + [
'user_id' => auth()->id()
]);
Because you don't have to set post_id manually. And user_id you get from authenticated user. Aslo post you have as a route parameter.
Please sign in or create an account to participate in this conversation.