2016-08-17 45 views
0

我是Laravel的新手,我創建了一個登錄表單,它將通過Ajax進行驗證。現在的問題是,當我使用Auth :: login($ user)它似乎沒有登錄該用戶的電子郵件和密碼驗證後。在下面檢查我的代碼。Laravel Auth ::登錄不能在AJAX請求上工作

JS

$('#loginform').on('submit', function(event){ 
    var token = $('#loginform input[name="_token"]').val(); 
    var email = $.trim($('#loginform #email').val()); 
    var password = $.trim($('#loginform #password').val()); 
    $.post("/checklogin", 
    { 
    _token: token, 
    email: email, 
    password: password, 
    }, 
    function(data){ 
     if(data == "success"){ 
     window.location.reload(); 
     } else { 
     $('#loginform .error').text(data); 
     } 
    }); 
    event.preventDefault(); 
}); 

CheckLoginController

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Auth; 
use App\Http\Requests; 
use App\User as User; 
use Hash; 

class CheckLoginController extends Controller 
{ 
    public function check(Request $request) 
    { 
     if($request->ajax()) : 
      $user = User::where('email', '=', $_POST['email'])->first(); 
      if($user) : 
       //check password 
       if(Hash::check($_POST['password'], $user->password)) : 
        Auth::login($user); 
        echo "success"; 
       else : 
        echo "Invalid username/password"; 
       endif; 
      endif; 
     endif; 
    } 
} 

任何人,請幫助。

+0

的輸出是什麼'的console.log(數據)'在你的Ajax代碼'功能(數據)' – xmhafiz

+0

@ h44f33z控制檯輸出「成功」,但仍是用戶沒有登錄in。 –

+0

也許可以嘗試使用'location.href'而不是'window.location.reload();' – xmhafiz

回答

0

我認爲最好用attempt函數來檢查電子郵件和密碼。還使用laravel Request獲得輸入

if ($request->ajax()) { 
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) { 
     // Authentication passed... 
     return 'success'; 
    } 
    else { 
     return 'Invalid username/password'; 
    } 

} 
+0

噢是會改變這一點。 ** Auth :: login($ user)**怎麼樣? –

+0

抱歉@ClydeScope,我的錯誤,我沒有注意到你已經使用'Hash :: check'進行密碼檢查。所以'Auth :: login'應該可以工作,除了'attempt'更簡單 – xmhafiz