Skip to content

Add a commentable structure to any model

MisterDebug edited this page Aug 29, 2023 · 4 revisions

Add a commentable structure to any model

With the command make:commentable, you can add a commentable feature to any model.

For example in a real life scenario, you want to add comments to a Post model

Commentable generator command :

Let's create your Post CRUD : image

Imagine, you want to add the comment block in your view posts/show.blade.php

@extends('default')

@section('content')
    <h1>{{ $post->title }}</h1>
    {!! nl2br($post->content) !!}
@stop

Now let's add the comment block

Add somewhere in your show page {{comment_here}} like this :

    <h1>{{ $post->title }}</h1>
    {!! nl2br($post->content) !!}
    <br><br>
    {{comment_here}}

image

Screenshots

And voilà, you have a comment block in your show page

image

Migration

A migration file is created in your database/migrations directory. If necessary edit it and run :

php artisan migrate

Routes

To create routes for this new controller, you can do the following:

Route::post('posts/{post}/comments', [CommentsController::class, 'store'])->name('comments.store');
Route::delete('comments/{id}', [CommentsController::class, 'destroy'])->name('comments.destroy');

Remove

You can delete all files (except migrations) created by the make:commentable command at any time. You don't need to remove all files manually.

To delete files, you can use the following command:

php artisan rm:commentable nameCommentable --force

php artisan rm:commentable comment --force (in our example)

The --force flag (optional) can be used to delete all files without confirmation.