I like to use ajax to insert into database and get back to show it. I have ajax like this
$.ajax({
method: 'POST',
url: "{{ route('comments.store') }}",
data: {
comment: 1,
comment_text: comment_text,
post_id: post_id,
"_token": "{{ csrf_token() }}"
});
and in Url route('comments.store) is protect by middleware('auth') in my controller
public function __construct()
{
$this->middleware('auth')->except(['index']);
}
public function store( Request $request ) {
if(Auth::check()){
if ( isset( $request->comment ) ) {
$comment = new Comment( [
'comment' => $request->comment_text,
'user_id' => Auth::id(),
'post_id' => $request->post_id
] );
$comment->save();
$comments = Comment::find( $comment->id );
return response( $comments );
}
}
return redirect()->route( 'home.post.show', $request->post_id );
}
when the user is logged it worked normal and response $comment row.
but when user is not logged the middleware not redirect user to logging page and it response error "unauthenticated".
how to resolve it need help. Thanks You..
window.location
– B. Desai