我第一次尝试 Laravel。我现在正在注册后登录用户,但似乎身份验证助手总是给我空值
这是代码
//REGISTERCONTROLLER
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
class RegisterController extends Controller
{
public function index(){
return view('auth.register');
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'username' => 'required|max:255',
'email' => 'required|email|max:255',
'password' => 'required|confirmed',
]);
User::create([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
auth()->attempt($request->only('email', 'password'));
return redirect()->route('dashboard');
}
}
这是仪表板控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index(){
dd(auth()->user());
return view('dashboard');
}
}
这里是路由 web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\Auth\RegisterController;
Route::get('/dashboard',[DashboardController::class, 'index'])->name('dashboard');
Route::get('/register',[RegisterController::class, 'index'])->name('register');
Route::post('/register',[RegisterController::class, 'store']);
Route::get('/posts', function () {
return view('posts.index');
});
另一件事,根据 VSCode,RegisterController 中的“尝试”一词似乎未定义
答案 0 :(得分:1)
那是因为 Auth::attempt 使用 bcrypt 对密码进行哈希处理,所以如果您的数据库中的密码未经过哈希处理(bcrypted),则尝试方法将始终失败,因为密码永远不会匹配。 请在注册您的用户之前尝试对密码进行哈希处理,并告诉我这是否可以解决问题
答案 1 :(得分:1)
这样做:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class DashboardController extends Controller
{
public function index(){
$user = Auth::user(); //this will return the authenticated user
return view('dashboard');
}
}
答案 2 :(得分:1)
我认为你需要改变:
$password = Hash::make($request->password);
User::create([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
'password' => $password,
]);
auth()->attempt('email' => $request->email, 'password' => $password);
if (Auth::attempt(['email' => $request->email, 'password' => $password])) {
// Authentication passed...
return view('dashboard');
}
答案 3 :(得分:0)
我更新了 VSCode,然后它突然工作正常。我什么都没做。