I am newbie in laravel and I get internal server error when i use ajax . I found when I want to save data(comment object) in database i have got this error exactly when I write this line:
$request->Post()->comments()->save($comment);
in the controller file.I attach all necessary code here.is there any body to help me please?
route.php
Route::post('/savecomment',[
'uses'=>'CommentController@postCreateComment',
'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 part
<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>
comment class
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
post class
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');
}
}
I think $comment->save(); will be ok.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.