lundi 4 novembre 2019

How to redirect to login after ajax call in Laravel?

I have a like button that is visible to all users, but i only want authenticated users to be able to like and unlike the product. If a guest tries to like, i would like to redirect them to login page.

Blade File

 <div style="display: " id="deletefavourite"onClick="deleteFromFavourites(, )"> unlike </div>
<div style=" display: " id="addfavourites" onClick="addToFavourites(, )" > like </div>

Javascript

  function addToFavourites(productid, userid) {
$.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

$.ajax({
method: 'post',
url: `/product/like/${productid}`,
data: {
    'user_id': userid,
    'product_id': productid,
},
success: function () {
    // hide add button
console.log($('#addfavourites' + productid));
    $('#addfavourites' + productid).show();
    // show delete button
    $('#deletefavourite' + productid).show();
},
error: function (XMLHttpRequest) {
    // handle error
}
});

}

Like Controller

  public function likeProduct($id)
{


    if(Auth::check()){
    $this->handleLike(Product::class, $id);
    return redirect()->back();
    }
    else{
        return redirect()->route('login')
    }
}

public function handleLike($type, $id)
{
    $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($id)->whereUserId(Auth::id())->first();

    if (is_null($existing_like)) {
        Like::create([
            'user_id'       => Auth::id(),
            'likeable_id'   => $id,
            'product_id'   => $id,
            'likeable_type' => $type,
        ]);
    } else {
        if (is_null($existing_like->deleted_at)) {
            $existing_like->delete();
        } else {
            $existing_like->restore();
        }
    }
}

I tried to (Auth::check() on controller but this only hides the button. How can i solve this problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire