0

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?

Adnan
  • 3,129
  • 6
  • 31
  • 36
  • If you really want to reduce the extra query burden then create a job and let the queue handle the extra burden. – jogesh_pi Dec 11 '19 at 12:14

2 Answers2

1

Maybe you can consider this on related model:

/**
     * Save auth user on create
     */
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $userID = auth()->id();
            $model->author_id = $userID;
        });
    }
knubbe
  • 1,132
  • 2
  • 12
  • 21
1

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.

MomoDerDodo
  • 138
  • 9