Wednesday, March 29, 2017

Creating and returning a model with a relationship in Laravel

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']);
}



via SimpleJ

Advertisement