Home > database >  gor error message when deleteing comment in Laravel project
gor error message when deleteing comment in Laravel project

Time:09-27

working with Laravel 6 project and I have following CommentController,

public function update(Request $request, $id)
    {
        $comment = Comment::find($id);

        $this->validate($request, array('comment' => 'required'));

        $comment->comment = $request->comment;
        $comment->save();

        Session::flash('success','Comment Created');

        return redirect()->route('posts.show', $comment->post->id);
    }

    public function delete($id)
    {
        $comment = Comment::find($id);
        return view('comments.delete')->withComment($comment);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $comment = Comment::find($id);
        $post_id = $comment->post->id;
        $comment->delete();

        Session::flash('success','Deleted Comment');

        return redirect()->route('posts.show', $post_id);
    }

and My routes are as following

Route::delete('comments/{id}', ['uses' => 'CommentsController@destroy', 'as' => 'comments.destroy']);

Route::get('comments/{id}/delete', ['uses' => 'CommentsController@delete', 'as' => 'comments.delete']);

but when I try to delete comment got following validation error message The comment field is required.

how could I fix this problem here?

edit.blade.php

@section('content')
<div class="col-sm-6">
                <form action="{{ route('comments.destroy',  $comment->id) }}" method="post">
    @csrf
    {{ method_field('PUT') }}
    <button type="submit" class="btn btn-danger btn-block">Delete</button>
                </form>
            </div>
        </div>
    </div>

@endsection

CodePudding user response:

You need to change {{ method_field('PUT') }} to {{ method_field('DELETE') }} or use the built-in @method('delete')

Like this

@section('content')
<div class="col-sm-6">
                <form action="{{ route('comments.destroy',  $comment->id) }}" method="post">
    @csrf
    @method('delete')
    <button type="submit" class="btn btn-danger btn-block">Delete</button>
                </form>
            </div>
        </div>
    </div>

@endsection

CodePudding user response:

$this->validate($request, array('comment' => 'required'));

In your blade view, if you are not posting a comment in your form, you will be facing this error The comment field is required

Make sure you are posting a comment, or any typo's.

Posting your blade view would help us alot more.

  • Related