Return a model with it's relationship when saving

Submitted by m4nuC - 3 years ago

When saving/updating a model you might want to get a JSON response that includes some relationship data as well.

public function store()
{
    $inputs = Input::all();
    $post = new Post;
    $post->fill($inputs);
	// Here we add the many to many model ID for he relationship
    $post->user_id = Auth::user()->user_id;
    // Now by calling the relationship we can make sure that the user data will be present in the response
    $post->user;
    return $post->save()
}

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks