猿问

如何使用 laravel 5.4 通过 jQuery/ajax 创建登录/注销

我是 Laravel 的新手,我只是通过 jQuery/ajax 创建登录。根据我的说法,它的工作完美代码如下:


查看:login.blade.php


<script>

    $(document).ready(function(){

        $("#submit").click(function(e){

            e.preventDefault();

            email = $("#email").val();

            password = $("#password").val();

            $.ajax({

                type:"POST",

                data:{"email":email, "password":password, "_token":"{{csrf_token()}}"},

                url:"{{URL::to('login_redirect')}}",

                success:function(data){

                    if (typeof data !== 'object') {

                        data = JSON.parse(data);

                    }

                    if (data.redirect) 

                    {

                        window.location.replace(data.redirect);

                    } 

                    else 

                    {

                        $("#success").html('<p style="color:red;">' + data.error + '</p>');

                    }

                }

            });

        });

    });

</script> 

<div id="success"></div>

<input type="text" name="email" id="email" placeholder="Email">

<input type="password" name="password" id="password" placeholder="Password">

<input type="submit" name="submit" id="submit" class="btn btn-primary">

控制器:Mycontroller.php


<?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Http\Controllers\Controller;

    use App\Http\Requests;

    use Auth;

    use Session;

    use DB;


现在,问题是当我单击注销按钮时,它会将我重定向到登录页面,这很好,但是当我直接浏览dashboard我的 url 上的页面而没有登录时,它再次访问,这是错误的。我希望一旦用户注销它就不能dashboard直接访问。那么,我该怎么做呢?请帮我。


蝴蝶不菲
浏览 200回答 1
1回答

跃然一笑

您应该需要在仪表板中检查用户的登录状态。简单来说,您可以尝试以下答案。在使用 Laravel 时,为什么不能使用该middleware属性?中间件提供了一种方便的机制来过滤进入应用程序的 HTTP 请求。例如,Laravel 包含一个中间件,用于验证您的应用程序的用户是否已通过身份验证。如果用户未通过身份验证,中间件会将用户重定向到登录屏幕。但是,如果用户通过了身份验证,中间件将允许请求进一步进入应用程序。public function dashboard(){&nbsp; &nbsp; $user = Session::get('user');&nbsp; &nbsp; if($user)&nbsp; &nbsp; &nbsp; &nbsp;return view('user.dashboard',['data'=>$user]);&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp;return redirect('/login');}
随时随地看视频慕课网APP
我要回答