I have a couple of endpoints for getting/posting comments on notes in this application.
The GET
endpoint uses Eloquent's with
method to include the comments' author data with the response:
public function getComments(Note $note) {
return $note->comments()->with(['author'])->get();
}
How can I also include the author data when creating/returning an Eloquent model? Here is my current method:
public function postComment(Note $note, Request $request) {
$user = $this->appUserRepo->getFromRequest($request);
$text = $request->text;
$comment = $note->comments()->create([
'app_user_id' => $user->id,
'text' => $text
]);
return $comment;
}
I'm looking for something like this (but this doesn't work):
public function postComment(Note $note, Request $request) {
$user = $this->appUserRepo->getFromRequest($request);
$text = $request->text;
$comment = $note->comments()->create([
'app_user_id' => $user->id,
'text' => $text
]);
return $comment->with(['author']);
}
To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result. Let's understand the one to one relationship through an example. First, we add the new column (user_id) in an existing table named as posts.
One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)
You should try using:
$comment->load('author');
return $comment;
to load author
relationship for comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With