Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

himala's avatar

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!!

0 likes
2 replies
MichalOravec's avatar
Level 75

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.

1 like

Please or to participate in this conversation.