Search code examples
javascriptlaravelvue.jslaravel-5.3vuejs2

How to redirect to login page if unauthorized user try to click? (vue.js)


My code is like this :

<script>
    export default{
        props:['idStore'],
        methods:{
            addFavoriteStore(event){
                $(function () {
                    $(document).ajaxError(function (e, xhr, settings) {
                        if (xhr.status == 401) {
                            window.Laravel.baseUrl+'/login'
                        }
                        else {
                            event.target.disabled = true
                            const payload= {id_store: this.idStore}
                            this.$store.dispatch('addFavoriteStore', payload)

                            setTimeout(function () {
                                location.reload(true)
                            }, 1500)
                        }
                    });
                });
            }
        }
    }
</script>

When click favorite button, it will call addFavoriteStore method

After run addFavoriteStore method, I will call condition to check unauthorized user or not. I try using condition like that, but it does not work. I check on the console, no error

Why the condition not working?


Solution

  • @moses-toh so glad my suggestions worked :-).

    So going through it all you as you where using laravel and the blade syntax you can use Blade/PHP to check if the user is logged in or not and supply the relivent Button/Message. So like you have done:

       @if (Auth::user())
         <favorite-button>&heart; Favorite</favorite-button>
       @else
         <a href="{{route('login')}}">Login To Favorite</a>
       @endif
    

    Hope this is ok.