I am trying to post some data to the database using vuejs and laravel. below are the code
html part:
<div class="field mini">
<textarea required v-model="newComment.text" placeholder="Write a comment" id="comment_text" name="comment_text"></textarea>
</div>
<button class="ui blue labeled submit icon button" @click.prevent="postComment()">
<i class="icon edit"></i> Add Reply
</button>
the Vuejs part
<script>
Vue.component('comments',{
template: '#comment-vue-template',
data:() => {
return {
comments: [],
newComment: {
'text': ''
}
}
},
created: function() {
this.getComments();
},
methods: {
getComments() {
this.$http.get('comments').then(response => {
this.comments = response.body
});
setTimeout(this.getComments,1000);
},
postComment() {
this.$http.post('comments ').then(response => {
this.newComment = {
'text': ''
};
this.getComments();
})
}
}
});
new Vue({
el:'#app',
});
</script>
the route part(web.php)
Route::resource('comments', 'CommentsController');
Routelist
| | POST | comments | comments.store | App\Http\Controllers\CommentsController@store | web,auth |
| | GET|HEAD | comments | comments.index | App\Http\Controllers\CommentsController@index | web,auth |
| | GET|HEAD | comments/create | comments.create | App\Http\Controllers\CommentsController@create | web,auth |
| | GET|HEAD | comments/{comment} | comments.show | App\Http\Controllers\CommentsController@show | web,auth |
| | PUT|PATCH | comments/{comment} | comments.update | App\Http\Controllers\CommentsController@update | web,auth |
| | DELETE | comments/{comment} | comments.destroy | App\Http\Controllers\CommentsController@destroy | web,auth |
| | GET|HEAD | comments/{comment}/edit | comments.edit | App\Http\Controllers\CommentsController@edit | web,auth
and the CommentsController
public function store(Request $request)
{
$owner = Auth::User();
$comment = new Comment;
$comment->posted = Carbon::now();
$comment->text = $request->comment_text;
$comment->owner = array('id'=>$owner->id, 'name'=>$owner->name, 'avatar'=>$owner->avatar);
$comment->save();
}
I tried the api route and the normal route but it does not work. i keep getting
method not allowed
even when the resource route is present in the web.php. Data gets loaded correctly though. Where is the mistake please. Thank you in advance.
via Aatish Kumar