Home > database >  Destroy method doesn't redirect to route
Destroy method doesn't redirect to route

Time:04-20

I am trying to delete data from comments.index:

<a href="{{route('comments.create', ['id'=>$post->id])}}">Create Comment</a>
    @foreach ($comments as $comment)
        @if ($comment->post_id == $post->id)
        <div >
            <div >
                <p>{{$comment->text}}</p>
            </div>
            <a href="{{route('comments.edit', $comment->id)}}" >Edit</a>
            <form action="{{ route('comments.destroy', $comment->post_id) }}" method="POST">
                @csrf
                @method('delete')
                <div >
                    <input type="submit"  value="Drop Me!"/>
                </div>
            </form>
        </div>
        @endif
    @endforeach

The program goes to route:

Route::delete('/delete_comments/{id}', [CommentController::class, 'destroy'])->name('comments.destroy');

The problem here is that it doesn't get to destroy function and it doesn't redirect back. In controller I got for destroy method:

public function destroy($id)
{
    //
    $comment = Comment::FindOrFail($id);
    $comment->delete();
    return redirect()->route('comments.index', ['id'=>$id])->with('message', 'Comment deleted');
}

Which should go to route:

Route::get('/get_comments/{id}', [CommentController::class, 'showByPost'])->name('comments.index');

This has the function:

public function showByPost($id){
    $comments = Comment::all();
    $post = Post::FindOrFail($id);
    // dd($user);
    return view('comments.index', ['post'=>$post, 'comments'=>$comments]);
}

CodePudding user response:

You can simply get your data like this:

$data = YOUR_MODEL::findOrFail($id);

then:

    $data->delete();

You need to get the $id like what you did up here.

CodePudding user response:

first: you must check you compiled html, see realpath on page for :action="{{ route('comments.destroy', $comment->post_id) }}"

second : when you click submit button, you can use chrome to view you post data;

third: check you request url and response data (headers and body)

  • Related