Laravel 6页面重载后Session丢失问题求助
Hey there, let's tackle that session issue where your user's email disappears after refreshing the user panel! The core problem here is how you're passing session data, plus a couple of small fixes to make your login code more robust.
Why the Session Disappears
When you use ->with('status', $userData) in your redirect, Laravel creates flash session data—this is only meant to last for the next single request. That's why it shows up the first time you land on the user panel, but vanishes when you refresh (since that's a second request).
Step 1: Fix the Login Controller
First, let's clean up your login logic to handle edge cases (like non-existent users) and use proper session persistence instead of flash data. Also, stop using md5 for passwords—Laravel has built-in secure hashing that you should use instead:
// LoginController use Illuminate\Support\Facades\Hash; // Add this at the top public function signin(Request $r) { // First, validate input (better than manual empty checks) $r->validate([ 'email' => 'required|email', 'password' => 'required' ]); $userInfo = DB::table('users')->where('email', $r->email)->first(); // Handle case where user doesn't exist if (!$userInfo) { return redirect('/login')->with('error', 'Invalid email or password'); } // Use Laravel's secure hash check (ensure passwords are hashed with Hash::make() on registration!) if (Hash::check($r->password, $userInfo->password)) { // Store user data in a persistent session $r->session()->put('userData', $userInfo->email); return redirect('/userpanel'); } else { return redirect('/login')->with('error', 'Invalid email or password'); } }
Step 2: Update the Blade Template to Use Persistent Session
Instead of relying on the flash status data, directly pull the persistent userData session you stored. Add a check to only show the alert if the user is logged in:
@if(session('userData')) <div class="alert alert-success d-block"> <div id="userEmail">{{ session('userData') }}</div> </div> @endif
Bonus: Secure the User Panel
Add a check in your HomeController to restrict access to logged-in users only:
// HomeController public function user_index() { // Redirect to login if no active session exists if (!session()->has('userData')) { return redirect('/login'); } $data = DB::table('personals') ->join('companies', 'personals.companyId', 'companies.id') ->get(); return view('userDashboard')->with(['data' => $data]); }
Key Takeaways
- Flash session data (
->with()) is for one-time messages (like success/error alerts), not persistent user data. - Always use Laravel's
Hashfacade for password security—md5 is outdated and insecure. - Handle edge cases (like non-existent users) to avoid unexpected errors.
内容的提问来源于stack exchange,提问作者Russel Monzur

