Image not found

Laravel comment & reply system

Comment (0)

Admin

251


Step 1 : Install Laravel

 

 composer create-project --prefer-dist laravel/laravel blog

 

Step 2: Update Database Configuration 

 

.env 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

 

Step 3: Create Post and Comment Table 

php artisan make:migration create_posts_comments_table 

 

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreatePostsCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
            $table->softDeletes();
        });
   
        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.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
        Schema::dropIfExists('comments');
    }
}

 

php artisan migrate 

 

Step 4: Create Model 

 

php artisan make:model Post 

 

 

app/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title', 'body'];
    
    /**
     * The has Many Relationship
     *
     * @var array
     */
    public function comments()
    {
        return $this->hasMany(Comment::class)->whereNull('parent_id');
    }
}

 

 php artisan make:model Comment

 

app/Comment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    protected $dates = ['deleted_at'];
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
        protected $fillable = ['user_id', 'post_id', 'parent_id', 'body'];
    /**
    * The belongs to Relationship
    *
    * @var array
    */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    /**
    * The has Many Relationship
    *
    * @var array
    */
    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

 

Step 5: Create Controller 

 

php artisan make:controller PostController 

 

app/Http/Controllers/PostController 

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }
    /**
    * Show the form for creating a new resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function create()
    {
        return view('posts.create');
    }
    /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    public function store(Request $request)
    {
        $request->validate([
        'title'=>'required',
        'body'=>'required',
        ]);
        Post::create($request->all());
        return redirect()->route('posts.index');
    }
    /**
    * Show the form for creating a new resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function show($id)
    {
        $post = Post::find($id);
        // dd($post);
        return view('posts.show', compact('post'));
    }
}

 

php artisan make:controller CommentController 

 

app/Http/Controllers/CommentController 

<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Comment;
   
class CommentController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
    	$request->validate([
            'body'=>'required',
        ]);
   
        $input = $request->all();
        $input['user_id'] = auth()->user()->id;
    
        Comment::create($input);
   
        return back();
    }
}

 

Step 6: Create Blade Files 

 

1) index.blade.php

2) show.blade.php

3) create.blade.php

4) commentsDisplay.blade.php

resources/views/posts/index.blade.php

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>nijwel.xyz</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-md-12">
          <h1>Manage Posts</h1>
          <a href="" class="btn btn-success" style="float: right">Create Post</a>
          <table class="table table-bordered">
            <thead>
              <tr>
                <th width="80px">Id</th>
                <th>Title</th>
                <th width="150px">Action</th>
              </tr>
            </thead>
            <tbody>
            @foreach($posts as $post)
              <tr>
                <td>{{ $post->id }}</td>
                <td>{{ $post->title }}</td>
                <td>
                <a href="{{ route('posts.show', $post->id) }}" class="btn btn-primary">View Post</a>
                </td>
              </tr>
            @endforeach
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
  </body>
</html>

 

resources/views/posts/show.blade.php

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>nijwel.xyz</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
  </head>
  <body>
		<div class="container">
			<div class="row justify-content-center">
				<div class="col-md-8">
					<div class="card">
						<div class="card-body">
							<h3 class="text-center text-success">nijwel.xyz</h3>
							<br/>
							<h2>{{ $post->title }}</h2>
							<p>
								{{ $post->body }}
							</p>
							<hr />
							<h4>Display Comments</h4>

							@include('posts.commentDisplay', ['comments' => $post->comments, 'post_id' => $post->id])

							<hr />
							
							<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>
								<br>
								<div class="form-group">
									<input type="submit" class="btn btn-success" value="Add Comment" />
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
  </body>
</html>

 

resources/views/posts/create.blade.php 

@extends('welcome')
@section('content')
<div class="container">
	<div class="row justify-content-center">
		<div class="col-md-8">
			<div class="card">
				<div class="card-header">Create Post</div>
				<div class="card-body">
					<form method="post" action="{{ route('posts.store') }}">
					@csrf
						<div class="form-group">
							<label class="label">Post Title: </label>
							<input type="text" name="title" class="form-control" required/>
						</div>
						<div class="form-group">
							<label class="label">Post Body: </label>
							<textarea name="body" rows="10" cols="30" class="form-control" required></textarea>
						</div>
						<div class="form-group">
							<input type="submit" class="btn btn-success" />
						</div>
					</form>
				</div>
			</div>
		</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-warning" value="Reply" />
            </div>
        </form>
        @include('posts.commentsDisplay', ['comments' => $comment->replies])
    </div>
@endforeach

 

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
use App\Http\Controllers\CommentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return redirect()->route('posts.index');
});

Route::get('post/index',[PostController::class , 'index'])->name('posts.index');
Route::get('post/create',[PostController::class , 'create'])->name('posts.create');
Route::post('post/store',[PostController::class , 'store'])->name('posts.store');
Route::get('post/show/{id}',[PostController::class , 'show'])->name('posts.show');

Route::get('comment/index',[CommentController::class , 'index'])->name('comments.index');
Route::get('comment/create',[CommentController::class , 'create'])->name('comments.create');
Route::post('comment/store',[CommentController::class , 'store'])->name('comments.store');
Route::get('comment/show/{id}',[CommentController::class , 'show'])->name('comments.show');

 

Run this project :

 php artisan serve

Hope it will help... 

Thanks


Others Problem Fix Stroy



Comments (0)

Your Comment