2
votes

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..

1
what is your middleware codeRAUSHAN KUMAR
It is ajax request. Which do not auto redirect to any page. You need to check condition in success and then redirect using window.locationB. Desai

1 Answers

0
votes

Add an error callback function to your jQuery Ajax to redirect the user to the login page if Unauthorized

$.ajax({
    method: 'POST',
    url: "{{ route('comments.store') }}",
    data: {
        comment: 1,
        comment_text: comment_text,
        post_id: post_id,
        "_token": "{{ csrf_token() }}"
    },
    success: function (data) {

    },
    error : function (jqXHR, textStatus, errorThrown) {
        // User Not Logged In
        // 401 Unauthorized Response
        window.location.href = ' login page';
    }
});