Reputation: 27
I got MethodNotAllowedHttpException
error on my Laravel 5.2 project, while I was adding Add Comment section.
Here is my route:
Route::post('/posts/{post}/comments', 'CommentsController@store');
Here is my CommentsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use App\Http\Requests;
class CommentsController extends Controller
{
public function store(Post $post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post->id
]);
return back();
}
}
and here is my view:
@extends('layouts.master')
@section('content')
<div class="col-sm-8 blog-main">
<h1>{{ $post->title }}</h1>
{{ $post->body }}
<hr>
<h5>Comments</h5>
<div class="comments">
<ul class="list-group">
@foreach ($post->comments as $comment)
<li class="list-group-item">
<strong>
{{ $comment->created_at->diffForHumans() }}:
</strong>
{{ $comment->body }}
</li>
@endforeach
</ul>
</div>
<hr>
<!-- Add Comment -->
<div class="card">
<div class="card-block">
<form method="POST" action="/blog/public/posts/{{ $post->id }}/comments" >
<div class="form-group">
<textarea name="body" placeholder="Your Comment" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Comment</button>
</div>
</form>
</div>
</div>
</div>
@endsection
The variables $post
and $comment
passed successfully to the view as retrieving the content and comment is working fine, but when I try to submit a new comment I got MethodNotAllowedHttpException
.
Upvotes: 0
Views: 127
Reputation: 7972
Provide your route a name
Route::post('/posts/{post}/comments', 'CommentsController@store')->name('comments.create');
Add the csrf token and use the helper method route()
to access the route in your form
<form method="POST" action="{{ route('comments.create', ['post' => $post->id]) }}" >
{{ csrf_field() }}
<div class="form-group">
<textarea name="body" placeholder="Your Comment" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Comment</button>
</div>
</form>
Change your function signature
public function store($post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post
]);
return back();
}
Upvotes: 1
Reputation: 883
your form action should be like this
/posts/{{ $post->id }}/comments
Upvotes: 1