#the livewire componet is not updated after adding a new comment

3 messages · Page 1 of 1 (latest)

errant siren
#

hi i have a livewire component for storing the comment for user and showing the result immediately without refreshing the page but what happens is that when i add a comment this comment is not appear unless i refreshed the page manually while it is suppose to apper immidiatly and here is the code

<?php

namespace App\Http\Livewire;

use App\Models\Comment;
use Livewire\Component;

class Comments extends Component
{
    public $comments;

    public $comment;

    public $user_id = 1;

    public function mount($comments): void
    {
        $this->comments = $comments;
    }

    public function store()
    {
        $created_comment = Comment::create([
            'body' => $this->comment,
            'user_id' => $this->user_id
        ]);
        return $created_comment->save();
    }

    public function render()
    {
        return view('livewire.comments');
    }
}

<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use Illuminate\Http\Request;

class CommentsController extends Controller
{

    public function index(){
        return view('comments',[
            'title'=>'index',
            'comments'=> Comment::with('author')->get()]);
    }
}
#
<div wire:submit.prevent="store" wire:key="{{ time() }}">
    <form  class="my-4 flex flex-col">
        <input type="text" class="w-full rounded border shadow p-2 mr-2 my-2" placeholder="What's in your mind" wire:model="comment">
        @error('body') <span class="text-red-600">{{ $message }}</span> @enderror
        <div class="py-2">
            <button  class="p-2 bg-blue-500 w-20 rounded shadow text-white">Add</button>
        </div>
    </form>
    @foreach($comments as $comment)
        <div class="border-4 rounded-lg p-5 mb-6">
            <div class="flex justify-between">
                <h1 class="font-bold text-lg basis-2/12">{{$comment->author->name}}</h1>
                <p class="text-slate-300 basis-10/12 mt-1">{{ $comment->created_at->diffForHumans()  }}</p>
            </div>
            <div>
                <p>
                    {{$comment->body}}
                </p>
            </div>
        </div>
    @endforeach
</div>

#
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Live-wire</title>
    @vite('resources/css/app.css')
    <livewire:styles />
    <livewire:scripts />
    @vite('resources/js/app.js')
</head>
<body class="">
     <div class="flex flex-col m-9">
         <h1 class="font-bold text-3xl mt-9">Comments</h1>
         <livewire:comments :comments="$comments"/>
     </div>

</body>
</html>