I've been watching a comment livewire tutorial from codecoure. Everything worked fine till a form that will store the comment is not going through. I tried dd, but I get nothing. In the url after the slug it says comment=whateverItyped. i've been using this tutorial in a story posting board, but I'm clueless where the error is. I've even copied and pasted the exact same form and method but nothing goes through the form.
The form:
<div class="min-w-0 flex-1">
<form wire:submit.prevent="postComment">
<div>
<label for="comment" class="sr-only">Comment body</label>
<textarea id="comment" name="comment" rows="3"
class="shadow-sm block w-full focus:ring-blue-500 focus:border-blue-500 border-gray-300 rounded-md @error('newCommentState.body') border-red-500 @enderror"
placeholder="Write something"
wire:model.defer="newCommentState.body">
</textarea>
@error('newCommentState.body')
<p class="mt-2 text-sm text-red-500">{{ $message }}</p>
@enderror
</div>
<div class="mt-3 flex items-center justify-between">
<button type="submit" class="inline-flex items-center justify-center px-4 py-2 border border-transparent font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
Comment
</button>
</div>
</form>
</div>
Since I'm clueless where this error is. I don't know what more I should post than the form. There is anohter method that gets the comments, and that works fine. I think it is something with the post request but I'm unsure since I'm new to livewire
namespace App\Http\Livewire;
use Livewire\Component;
class Comments extends Component
{
public $model;
public function postComment()
{
$this->validate([
'newCommentState.body' => 'required'
]);
$comment = $this->model->comments()->make($this->newCommentState);
$comment->user()->associate(auth()->user());
$comment->save();
$this->newCommentState = [
'body' => ''
];
$this->goToPage(1);
}
public function render()
{
$comments = $this->model
->comments()
->with('user', 'children.user', 'children.children')
->parent()
->latest()
->get();
return view('livewire.comments', [
'comments' => $comments
]);
}
}
It seems you are using $newCommentState
, but never declares it.
Add a new attribute public $newCommentState;
.
I would also create a method like that:
// this will initialize $newCommentState
public function mount() {
$this->newCommentState = [
'body' => ''
];
}