Laravel 9 Multiple User Comments CRUD Eloquent Relationship Example

Hi Artisan

Today i will explain you example tutorial of Laravel 8 Multiple User Comments CRUD With one to many(hasMany) Eloquent Relationship Example. you will learn . I will give simple example for how to use and implement hasMany Eloquent relationship using multiple user comment and as you can delete this comment as you wish.i will fully explain how to work this tutorial follow my all step

In this tutorial i will share some important point to related this article

Here i will give you full example for Multiple user comments Crud operation using has many relationship. So let's visually perceive bellow step by step:

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.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 Two Migration Table

in this third step we will create two migration table using simple command one is "posts" and another is "comments" you can check bellow code i wish you can understand.

database/migrations/2021_05_27_114422_create_posts_table.php
<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('ptitle');
            $table->string('pbody');
            $table->timestamps();
        });
    }

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

Now after another create table "comments" you can check bellow code.

database/migrations/2021_05_28_051449_create_comments_table.php
<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->string("message");
            $table->timestamps();
        });
    }

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

Step 4: Make Two Models

after in fourth step we will create a two model using a simple command one is "Post" and another is "Comment" you can check bellow code you can copy that

Here, we will engender Utilizer and Accommodation table model. we will additionally use "hasMany()" for relationship of both model.

app/Models/Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'ptitle',
        'pbody',
    ];

     public function comment()
    {
        return $this->hasMany(Comment::class);
    }

}

app/Models/Comment.php
<?php

namespace App\Models;

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

class Comment extends Model
{
    use HasFactory;

    protected $fillable = [
        'post_id',
        'message',
    ];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
    
}
Step : 5 Create PostController

After in this step we will create a PostController using simple command.

app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Post;
use App\Models\Comment;

class PostController extends Controller
{
    //
    /**
     * Write code on Method
     *
     * @return response()
     */

    public function index()
    {
      $posts = Post::get();
      return view('post.index', compact('posts'));
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        
        $input = $request->all();
        Post::create($input);

        return redirect()->route('post.index');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show($id)
    {
        $post = Post::find($id);
        return view('post.show',compact('post'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function comment(Request $request)
    {
        $input = $request->all();
        Comment::create($input);

        return redirect()->route('post.index');    
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function showcomment($id)
    {
        $comments = Post::find($id)->comment;
        return view('post.showcomment',compact('comments'));    
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function destory(Request $request,$id)
    {
        $input = $request->all();

        $comments = Comment::find($id);
        $comments->delete($input);
        
        return redirect()->route('post.index');
    }

}

Step : 6 Create Route

In this step we will create a route in routes directory in web.php file include PostController and make a route and different different methods.

routes/web.php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

// Comments Route
Route::post('post/comment', [PostController::class ,"comment"])-> name("post.comment");
Route::get('post/comment/{id}', [PostController::class ,"showcomment"])-> name("post.showcomment");
Route::delete('post/comment-delete/{id}', [PostController::class ,"destory"])->name("post.destory");

Step 7: Create Blade File

now In last step we can create a blade file in resources/views/post directory folder structure.

create.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
    
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h5>Create Post</h5>
                    </div>
                    <div class="card-body">
                        <form action="{{ route('post-store') }}" method="post">
                            @csrf
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="ptitle">Post Title</label>
                                        <input type="text" class="form-control" name="ptitle" id="ptitle">
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="pbody">Post Body</label>
                                        <textarea class="form-control" rows="3" name="pbody" id="pbody"></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <button class="btn btn-success" type="submit">Submit</button>
                                    <a href="{{ route('post.index') }}" class="btn btn-secondary" type="submit">Cancel</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
    
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="btnadd justify-content-end d-flex mb-2">
                    <a href=" {{ route('create') }} " class="btn btn-success"><i class="fas fa-plus"></i></a>
                </div>
                <div class="card">
                    <div class="card-header">
                        <h4>Laravel 8 Multiple User Comments CRUD With hasMany Eloquent Relationship Example - CodingTracker</h4>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>PostTitle</th>
                                    <th>PostBody</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>

                                @forelse ($posts as $key => $post)
                                <tr>
                                    <td>{{ ++$key }}</td>
                                    <td>{{ $post->ptitle }}</td>
                                    <td>{{ $post->pbody }}</td>
                                    <td width="15%">
                                        <a href="{{ route('post.show',$post->id) }}" class="btn btn-info text-white"><i class="fas fa-eye"></i></a>
                                        <a href="{{ route('post.showcomment',$post->id) }}" class="btn btn-success text-white"><i class="far fa-comment-dots"></i></a>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="5" class="text-center"> <h3>There are no data.</h3></td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> 
    </div>

</body>
</html>
show.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
    <div class="container mt-5 bg-white">
        <div class="btnback text-right mb-2">
            <a href="{{ route('post.index') }}" class="btn btn-secondary mt-2"><i class="fas fa-arrow-left"></i></a>
        </div>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-bordered">
                    <tr>
                        <th>Post Title</th>
                        <td>{{ $post->ptitle }}</td>
                    </tr>
                    <tr>
                        <th>Post Body</th>
                        <td>{{ $post->pbody }}</td>
                    </tr>
                    <tr>
                        <th >Comments</th>
                        <td>
                            <form action="{{ route('post.comment') }}" method="POST">
                                @csrf
                                <input type="hidden" name="post_id" value="{{ $post->id }}">
                                <textarea rows="4" class="form-control" name="message" id="message"></textarea>
                                <button class="btn btn-success mt-2" type="submit">Submit</button>
                            </form>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</body> 
</html>

showcomment.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
    
    <div class="container mt-5">
        <div class="btnback text-right mb-2">
            <a href="{{ route('post.index') }}" class="btn btn-secondary mt-2"><i class="fas fa-arrow-left"></i></a>
        </div>
        <div class="row">
            <div class="col-md-12 mx-auto">
                <div class="card">
                    <div class="card-header">
                        <h5>User Comments</h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <tr>
                                <th>Comment</th>
                                <th width="15%">Action</th>
                            </tr>
                                @foreach ($comments as $comment)
                                    <tr>
                                        <td>
                                            {{ $comment->message }}
                                        </td>
                                        <td>
                                            <form method="POST" action="{{ route('post.destory',$comment->id) }}" class="form-inline">
                                                  @csrf
                                                  @method('delete')
                                                  <button type="submit" class="btn btn-danger btn-icon">
                                                    <i class="far fa-trash-alt text-white" data-feather="delete"></i>
                                                  </button>
                                            </form>
                                        </td>
                                    </tr>
                                @endforeach
                        </table>
                    </div>
                </div>
            </div>
        </div> 
    </div>

</body>
</html>
php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/index

It will help you...

Post a Comment