Search code examples
laraveleloquentlaravel-events

What is the best way to add the authenticated user to a related model?


What is the best way to add the authenticated user to a related model?

If I wanted to add the authenticated user as the author on a post model whenever a new post is created, what would be the best way to do it?

Currently, I have the following which does the job but it runs an extra query (i.e 1. Create post. 2. Update post with author_id).

public function store(Request $request)
{
  $post = Post::create($request->all());
  $post→author()->associate($request->user());
  $post→save();

  return new PostResource($post);

} 

There must be a better way to do this. I was thinking of just adding all the attributes manually, with $post-author_id = $request→user()→id, and then calling $post-save(). However, I do not like the idea of having to manually write out all the other attributes of the post.

Another option I was thinking is by creating an event listener on the Post creating event. I do not know if this will reduce the need for an extra query.

What is the simplest solution?


Solution

  • Instead of using the create method, you could simply create a new instance of PostResource and fill it with author_id. So it would be a bundled query.

    public function store(Request $request) {
        $post = new Post($request->all());
        $post->author_id = Auth::user()->id;
        $post->save();
    
        return new PostResource($post);
    }
    

    I hope it helps.