Delete method cause 404 error ( nested component trouble )

I am making comments system. with two double livewire components.

outer component contains command-line component …

see following code…

in comments-section.blade.php

<div>
    @foreach ($post->comments as $comment)
        @livewire('comment-line', [
            'post' => $post,
            'comment' => $comment,
        ], key($comment->id))
    @endforeach
</div>

in CommandLine.php


public $post;
public $comment;

protected $listeners = [
    'setdelete'
];

public function render()
{
    return view('livewire.comment-line');
}

function mount( $post, $comment ) {
    $this->post = $post;
    $this->comment = $comment;
}

function setdelete( $commentid ){
    $comment = Comment::findOrFail( $commentid);
    $comment->delete();

}

in command-line.blade.php

<div 
    x-data="{  comment_id:null }"
    @setdelete="
        comment_id = $event.detail.comment_id ;
        if(  comment_id == {{ $comment->id }} ) {
            window.livewire.emit('setdelete', comment_id );
        }
    "
>
    {{ $comment->content }}
    <div 
        @click="$dispatch('setdelete', { comment_id : '{{ $comment->id }}' } ); "
    > DELETE !</div>

</div>

Whenever I trigger ‘setdelete’ on document, it show 404 error after deleting model.

Can you help me out?

hey @bingglex
you are putting Comment::findOrFail(...) method to find the comment and if there is no comment related to this id it cause 404 not found page this is the first thing.

The second thing you are making in command-line.blade.php file {comment_id: null} it may because of the error and passing null to the component file.

  • So try to dd() the $commentid) in the method setdelete and see the returned data
  • make sure you are passing the correct $commentid from the view into the controller.

Thanks for reply.

Have you tried with source code ?

yes. I checked it already.

$commentid is arrived correctly on livewire component .

and Comment::findOrFail(...) works fine too…

Any more idea ?

function setdelete( $commentid ){
    $comment = Comment::findOrFail( $commentid);
    $comment->delete();
    return back();
}

see this article

try

function setdelete( $commentid ){
    $comment = Comment::findOrFail( $commentid);
    $comment->delete();
    $this->comment = null;

}
2 Likes

why you set $this->comment to null
is there any specific reason?

@skywalker Because if $this->comment is an eloquent model then Livewire will try to re-hydrate it when rendering, but if that model is deleted then this is going to fail.

2 Likes

It is reasonable.

I got the point from your comment.

I wish there is doc on this nested component case.

livewire doc is too much simple for beginners.

make sense.
Thank you @snapey for the explanation.