我是laravel的新手,當我使用ajax時出現內部服務器錯誤。 我發現,當我要保存在數據庫中的數據(評論對象)當我寫這條線我有這個錯誤正是:(內部服務器錯誤)laravel和ajax
$request->Post()->comments()->save($comment);
在file.I附上所有必要的代碼控制器here.is有任何身體請幫助我?
route.php
Route::post('/savecomment',[
'uses'=>'[email protected]',
'as'=>'comment.save'
]);
commentController.php
public function postCreateComment(Request $request)
{
$this->validate($request,[
'commentBody'=>'required|max:1000'
]);
$comment=new Comment();
$comment->body=$request['commentbody'];
$comment->post_id=$request['postId'];
$message ='there was an error';
$request->Post()->comments()->save($comment);
$message='comment successfuly created';
//return redirect()->route('dashboard')->with(['message'=>$message]);
}
的jquery
$('[id^=comment-save]').on('click', function (event) {
event.preventDefault();
postId = $(this).parents('.post').attr('data-postId');
$.ajax({
method :'POST',
url: urlComment,
data:{postId:postId,_token:token,commentBody:$('#comment-body'+postId).val()}
})
.done(function(){
//change the page
});
HTML部分
<section class="row posts">
<div class="cod-md-6 col-md-offset-3">
<header><h3>what is other`s idea</h3></header>
@foreach($posts as $post)
<article class="post" data-postId='{{ $post->id}}'>
<p>
{{$post->body}}
</p>
<div class="info">
posted by {{$post->user->first_name}} in {{$post->created_at}}
</div>
<div class="interaction">
<a class="like" href="#">Like</a>|
<a class="dislike" href="#">Dislike</a>|
<a data-toggle="collapse" href="#collapseComment{{ $post->id }}" aria-expanded="false" aria-controls="">
comment
</a>
@if(Auth::user() == $post->user)
|<a data-toggle="modal" href="#edit-model" class="edit" >Edit</a>|
<a href="{{ route('post.delete',['post_id'=>$post->id])}}">Delete</a>
@endif
</div>
<div class="collapse" id="collapseComment{{ $post->id }}">
<div class="card card-block">
<input type="test" name="comment-body{{ $post->id }}" id="comment-body{{ $post->id }}" >
<button type="button" id="comment-save{{ $post->id }}" class="btn btn-primary">comment</button>
</div>
</div>
</article>
@endforeach
</div>
</section>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment.save') }}';
</script>
評論類
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
後級
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\user');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
「內部服務器錯誤」意味着請查看錯誤日誌以獲取詳細信息。 – jszobody
如果您需要調試幫助,請隔離問題並創建[mcve]。 –
在日誌文件中是wriiten:[2016-06-13 09:40:38] local.ERROR:異常'BadMethodCallException'消息'Method Post does not exist'。在H:\ wamp \ www \ sport \ vendor \ laravel \ framework \ src \ Illuminate \ Support \ Traits \ Macroable.php中:81 但是正如您在我的代碼中看到的,我有post()方法 – azar