Laravel中如何用Model实现Where查询及登录查询异常排查
Hey there! Let's break down what's causing your $user variable to return 1/0 instead of the user data, and fix it properly.
Why you're getting 1 or 0
The core issue is your current query uses a logical AND (&&) between two separate database calls:
$user = DB::table('users')->where('name', $request->name)->first() && DB::table('users')->where('password', $request->password)->first();
- Each
first()call returns either a user object (if found) ornull. - The
&&operator converts these results to boolean values: if both queries find something, it returnstrue(which becomes1in PHP), otherwisefalse(which becomes0). - On top of that, this logic is flawed: you're checking if any user has the provided name, and any user has the provided password—not that the same user has both!
Fix 1: Correct DB Facade Query
Combine both conditions into a single query to fetch the user that matches both name and password. This will return the actual user object (or null if no match):
$user = DB::table('users') ->where('name', $request->name) ->where('password', $request->password) ->first(); if ($user === null) { return redirect('/login'); } return view('user.dashboard', compact('user'));
Fix 2: Use Laravel's User Model (Recommended)
Laravel's Eloquent models make database queries cleaner and more maintainable. Assuming you have the default User model (located at app/Models/User.php):
- First, import the model at the top of your controller:
use App\Models\User;
- Then query the model directly:
$user = User::where('name', $request->name) ->where('password', $request->password) ->first(); // Or use an array of conditions for brevity: // $user = User::where(['name' => $request->name, 'password' => $request->password])->first(); if ($user === null) { return redirect('/login'); } return view('user.dashboard', compact('user'));
Critical Security Note: Never Store Plaintext Passwords!
Your current code compares plaintext passwords, which is a huge security risk. Laravel provides built-in password hashing and authentication tools to handle this safely:
- When registering users, hash the password:
use Illuminate\Support\Facades\Hash; // Store hashed password in the database $user = User::create([ 'name' => $request->name, 'password' => Hash::make($request->password), ]);
- When logging in, use
Hash::check()to verify the password, or better yet, use Laravel's built-in Auth system:
use Illuminate\Support\Facades\Auth; if (Auth::attempt(['name' => $request->name, 'password' => $request->password])) { // Authentication passed, get the logged-in user $user = Auth::user(); return view('user.dashboard', compact('user')); } return redirect('/login');
The Auth::attempt() method automatically handles password hashing verification and even sets up the user session for you.
内容的提问来源于stack exchange,提问作者Adil

