Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']);
}
like image 256
SimpleJ Avatar asked Mar 29 '17 17:03

SimpleJ


People also ask

How do you define a relationship in Laravel?

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.

How many types of relationships are there in Laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)


1 Answers

You should try using:

$comment->load('author');
return $comment;

to load author relationship for comment.

like image 105
Marcin Nabiałek Avatar answered Oct 07 '22 11:10

Marcin Nabiałek