简体   繁体   中英

How to create login/logout via jQuery/ajax using laravel 5.4

I am new in Laravel and I am simply create login via jQuery/ajax. According to me its work perfectly code mention below:

Views: 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">

contollers: 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;

    class Mycontroller extends Controller 
    {   
        public function login_redirect(Request $request)
        {
            $email = $request->input('email');
            $password = $request->input('password');
            $sql = DB::table('user')->where('email', '=', $email)->where('password', '=', $password)->count();
            if($sql > 0)
            {
                $query = DB::table('user')->where('email', '=', $email)->where('password', '=', $password)->get();
                Session::put('user', $query);
                if (!isset($_POST)) 
                {
                    header ("Location: dashboard");
                } 
                else 
                {
                    echo json_encode(array('redirect' => "dashboard"));
                }
            }
            else 
            {
                echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
            }
        }

        public function dashboard()
        {
            $user = Session::get('user');
            return view('user.dashboard',['data'=>$user]);
        }

        public function logout(Request $request) {
            Auth::logout();
            Session::flush();
            return redirect('/login');
        }
    }

views: dashboard.php

<?php
    if(empty($data))
    {
        header('location:{{url("login")}}');
    }
?>
@if (is_array($data) || is_object($data))
    @foreach($data as $row)
        <h3>Welcome, {{ $row->username }}</h3>
    @endforeach
@endif
<a href="{{url('logout')}}">Logout</a>

Now, the problem is that when I click on logout button it redirect me on login page which is fine but when I directly browse dashboard page on my url without login it again accessible which is wrong. I want once user logout it can't access dashboard directly. So, How can I do this? Please help me.

Thank You

You should need to check the user is login status in the dashboard. For simply, you can try the below answer. As using Laravel, why can't you use the middleware property?

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

public function dashboard()
{
    $user = Session::get('user');
    if($user)
       return view('user.dashboard',['data'=>$user]);
    else
       return redirect('/login');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM