如何在Laravel登出函数中获取登录时定义的$time变量值?
The $time variable you're creating in your BroadcastServiceProvider's channel closure is a local variable—it only exists within that function scope and isn't saved anywhere permanent. That's why you can't pull it into your logout method directly. Here's how to fix this by storing the timestamp when the user joins, then retrieving it later:
Step 1: Pass the Timestamp to Your UserInfo Storage Method
First, update the BroadcastServiceProvider to send the $time value to your storeUser method so it can be saved:
Broadcast::channel('chat', function ($user) { $ip = Request::ip(); $time = now(); if (auth()->check() && !session()->has('name')) { // Pass the join timestamp to storeUser UserInfo::storeUser($time); return [ 'user_id' => $user->id, 'ip' => $ip, 'name' => $user->name, 'joined' => $time, ]; } });
Step 2: Save the Timestamp to Your UserInfo Table
First, make sure your user_infos table has a column to store the join time. If not, create a migration:
php artisan make:migration add_joined_at_to_user_infos_table --table=user_infos
Open the generated migration file and add the timestamp column:
public function up() { Schema::table('user_infos', function (Blueprint $table) { $table->timestamp('joined_at')->nullable(); }); } public function down() { Schema::table('user_infos', function (Blueprint $table) { $table->dropColumn('joined_at'); }); }
Run the migration to apply the change:
php artisan migrate
Now update the storeUser method in your UserInfo model to save the passed timestamp:
public static function storeUser($joinedTime) { // Create or update the UserInfo record for the current user return self::updateOrCreate( ['user_id' => auth()->id()], ['joined_at' => $joinedTime] // Include any other fields you normally store here ); }
Step 3: Access the Timestamp in Your Logout Method
Now you can easily retrieve the saved join time in your logout function:
public function logout() { $id = auth()->id(); $user_info = \App\UserInfo::where('user_id', $id)->first(); // Access the saved join timestamp $joinedTime = $user_info->joined_at; // Use $joinedTime for whatever logic you need here $user_info->save(); auth()->logout(); session()->put('left', now()); return redirect('/'); }
Optional: Use an Accessor for Formatted Timestamps
If you want to format the timestamp automatically, add an accessor to your UserInfo model:
// In App\UserInfo use Carbon\Carbon; public function getJoinedAtFormattedAttribute() { return Carbon::parse($this->joined_at)->format('F j, Y g:i A'); }
Now you can use $user_info->joined_at_formatted to get a human-readable version of the join time.
内容的提问来源于stack exchange,提问作者Brad_Fresh

