M
M
moscowthebest2019-04-22 01:56:21
Laravel
moscowthebest, 2019-04-22 01:56:21

Is there a better way to do this?

There are tables and models as follows: Posts, Comments.
Inside the model, Post implemented a bunch:

public function comments()
{
    return $this->hasMany('App\Comment');
}

With the help of the following code, I get all the comments on the post.
$post->comments
Now for the problem...
This is the comment table:
$table->bigIncrements('id');
$table->string('body');
$table->integer('user_id');
$table->integer('post_id');
$table->timestamps();

As you can see, I can't find out the name of the author of the comment. The point is not only in the name, but also in other data. Don't dwell on it.
Okay, this is all solved. Binding in the Comment model...
public function user()
{
    return $this->belongsTo('App\User');
}

In the end, when I show Post, I have to write a lot of things ... And Laravel is a lazy framework, so I don’t know something.
How can this code be correctly implemented? I want an upgrade!
public function show(Post $post)
    {
        $comments = array();

        foreach ($post->comments as $comment) {

            $comment->user;

            array_push($comments, $comment);
            
        }

        $post['comments'] = $comments;

        return response()->json($post);
    }

Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question