Support the ongoing development of Laravel.io →
Database Eloquent Views
Last updated 1 year ago.
0

You already eagerloaded in the controller.
So in your view, just use $value->comments as comments => $cvalue

@foreach($posts as $key => $value)
    <span>{{ $value->user->username }}</span>
    <h1>{{ $value->post_title }}</h1>
    <p>{{ $value->post_body }}</p>
    @foreach($value->comments as $comments => $cvalue)
        {{ $cvalue->komentar }}
    @endforeach;
@endforeach

Edit: I think, in this case you can do this too

@foreach($posts as $post)
    <span>{{ $post->user->username }}</span>
    <h1>{{ $post->post_title }}</h1>
    <p>{{ $vpost->post_body }}</p>
    @foreach($post->comments as $comment)
        {{ $comment->komentar }}
    @endforeach;
@endforeach
Last updated 1 year ago.
0

Wow, just simple as that, great!!, Thanks for your reply. have a question, how did the laravel determined which comments should show on which post?? as you can see from code above, i'm passing the id_post in the model :

Post::find($value->id_post)->comments

did the laravel is auto creating pivot table?

Last updated 1 year ago.
0

No, you have to make a table for the comments.

which has an id, a body which contains the text of the comment, a commentable_id which will be the idea of the post and a commentable_type which will hold the model name. This way you can connect the comment table to several models.

Don't forget timestamps created_at and updated_at.

In your case, I think the migration would look something like this.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateCommentsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->text('komentar');
            $table->morph('commentable');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('comments');
    }
}

P.S. Made an addition to my previous reply

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

FazaMaula fazamaula Joined 7 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.