It looks like you're trying to use an attribute-based validation rule in your Livewire component, but you're not using it correctly. The #[Rule] attribute is not a standard way to define validation rules in Livewire. Instead, you should define a rules method that returns an array of validation rules.
Here's how you can update your Livewire component to include proper validation:
namespace App\Livewire;
use App\Models\Comment;
use App\Models\Post;
use Livewire\Component;
class CommentCreate extends Component
{
public $comment;
public Post $post;
public ?Comment $commentModel = null;
public ?Comment $parentComment = null;
protected function rules()
{
return [
'comment' => 'required|min:3|max:200',
];
}
public function mount(Post $post, $commentModel = null, $parentComment = null)
{
$this->post = $post;
$this->commentModel = $commentModel;
$this->comment = $commentModel ? $commentModel->comment : '';
$this->parentComment = $parentComment;
}
public function render()
{
return view('livewire.comment-create');
}
public function createComment()
{
$this->validate();
$user = auth()->user();
if (!$user) {
return $this->redirect('/login');
}
if ($this->commentModel) {
if ($this->commentModel->user_id != $user->id) {
return response('You are not allowed to perform this action', 403);
}
$this->commentModel->comment = $this->comment;
$this->commentModel->save();
$this->comment = '';
$this->dispatch('commentUpdated');
} else {
$comment = Comment::create([
'comment' => $this->comment,
'post_id' => $this->post->id,
'user_id' => $user->id,
'parent_id' => $this->parentComment ? $this->parentComment->id : null
]);
$this->dispatch('commentCreated', $comment->id);
$this->comment = '';
}
}
}
In the createComment method, I've added $this->validate(); which will trigger the validation rules defined in the rules method. If the validation fails, Livewire will automatically throw an exception and render the validation errors in the view.
Make sure your blade file is set up to display these validation errors. You can use the @error directive to show specific error messages:
<div>
<!-- Validation Errors -->
@error('comment')
<span class="text-red-500 text-xs">{{ $message }}</span>
@enderror
<!-- Rest of your form -->
</div>
With these changes, your Livewire component should now properly validate the comment input before saving it to the database.