我无法使用 Auth::attempt php laravel 登录

时间:2021-07-29 07:48:14

标签: php laravel

我从登录表单收到数据,但由于某种原因它没有被授权。数据正确保存到数据库中。我是 laravel 的新手,我完全不明白为什么会发生这种情况,但我想知道。 登录.blade.php

<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{

    public function login(Request $request){
        if(Auth::check()){
            return redirect(route('user.private'));
        }

$formFields = $request->only(['email','password']);
        if (Auth::attempt($formFields)){

            return redirect(route('user.private'));
        }
        return redirect(route('user.login'))->withErrors([

            'email' => 'Bad'
        ]);

    }
}

登录控制器.php:

<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{

    public function login(Request $request){
        if(Auth::check()){
            return redirect(route('user.private'));
        }

$formFields = $request->only(['email','password']);
        if (Auth::attempt($formFields)){

            return redirect(route('user.private'));
        }
        return redirect(route('user.login'))->withErrors([

            'email' => 'Bad'
        ]);

    }
}

web.php:

<?php
Route::name('user.')->group(function (){
    Route::view('/private','private')->middleware('auth')->name('private');
    Route::get('/login',function(){
        if(Auth::check()){
            return redirect(route('user.private'));
        }
//        Проверка на авторизацию пользователя. Если уже авторизован, то редирект на страницу профиля
        return view('login');
    })->name('login');
    Route::post('/login',[\App\Http\Controllers\LoginController::class,'login']);
    Route::get('/logout',function(){
        Auth::logout();
        return redirect('/');
    })->name('logout');
    Route::get('/registration', function () {
        if(Auth::check()){
            return redirect(route('user.private'));
        }
        return view('registration');
    })->name('registration');
    Route::post('/registration',[\App\Http\Controllers\RegisterController::class,'save']);
});

来自数据库 enter image description here 从启动/登录 enter image description here

3 个答案:

答案 0 :(得分:0)

看一下 Laravel 的文档,看起来你的代码有点不同:https://laravel.com/docs/8.x/authentication#authenticating-users

作为清理说明,我会删除 web.php 中的 Auth::check,因为您已将其包含在登录控制器中。

答案 1 :(得分:0)

数据库中的密码字段值不能明确,需要bcrypt。

到控制台运行php artisan tinker然后把bcrypt的结果作为字段的值

User::where('email','test1234@test')->update(['password' => bcrypt('test')]);

现在您可以使用 test1234@test 作为电子邮件和 test 作为密码登录

答案 2 :(得分:0)

密码必须通过 bcrypt 散列:

class User extends Model {

    public function setPasswordAttribute($value) {
         $this->attributes['password'] = bcrypt($value);
    }

}

所以你可以使用 simpy

Auth::attempt(array('email' => 'test1234@test', 'password' => 'test'));