Skip to content

Add a commentable structure to any model

MisterDebug edited this page May 20, 2023 · 4 revisions

Add a commentable structure to any model

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

Example in real life, you want to add comments on 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 your routes for this new controller, you can do this :

Route::post('comments/store/{post}', [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 by hand)

php artisan rm:commentable nameCommentable --force

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

--force (optional) can delete all files without confirmation

Clone this wiki locally