Flat comments in Laravel
database/migrations/2023_07_01_172202_create_comments_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->integer('parent_id')->unsigned()->nullable();
$table->text('body');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('comments');
}
};
resources/views/posts/show.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="pb-4 mb-4 fst-italic border-bottom">
<h1 class="blog-post-title mb-1">{{ $post->title }}</h1>
</div>
@include('posts.includes.manage')
<article class="blog-post">
<img class="d-block mb-3 featured" src="{{ url($post->featured_image) }}">dd
{!! $post->body !!}
</article>
<hr />
<h4>Display Comments</h4>
<hr />
@include('posts.commentsDisplay', ['comments' => $post->comments, 'post_id' => $post->id])
<h4>Add comment</h4>
<form method="post" action="{{ route('comments.store') }}">
@csrf
<div class="form-group">
<textarea class="form-control" name="body"></textarea>
<input type="hidden" name="post_id" value="{{ $post->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
@endsection
resources/views/posts/commentsDisplay.blade.php
@foreach($comments as $comment)
<div class="display-comment" @if($comment->parent_id != null) style="margin-left:40px;" @endif>
<strong>{{ $comment->user->name }}</strong>
<p>{{ $comment->body }}</p>
<a href="" id="reply"></a>
<form method="post" action="{{ route('comments.store') }}">
@csrf
<div class="form-group">
<input type="text" name="body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post_id }}" />
<input type="hidden" name="parent_id" value="{{ $comment->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Reply" />
</div>
<hr />
</form>
@include('posts.commentsDisplay', ['comments' => $comment->replies])
</div>
@endforeach
- Log in to post comments