如何删除Laravel 5中的会话

时间:2015-04-05 21:22:35

标签: php laravel-5

我正在尝试删除基本会话,但它不会删除。这是代码

welcome.blade.php

@if(Session::has('key'))             
    {{ Session::get('key')}}
    <a href="logout">Sign Out</a>

    @else
        please signin

    @endif
</div>

我不知道如何删除会话。这是我使用的那个,但它不起作用route.php

Route::get('/logout', function() {

   $vv =  Session::forget('key');
   if($vv)
   {
        return "signout";
   }
});

5 个答案:

答案 0 :(得分:16)

您应该使用此方法

 Route::get('/logout', function() {
 Session::forget('key');
  if(!Session::has('key'))
   {
      return "signout";
   }
 });

答案 1 :(得分:3)

您可以尝试使用Session::pull('key');

如果您想删除所有会话变量,可以使用Session::flush();

http://laravel.com/docs/5.0/session#session-usage

答案 2 :(得分:0)

Session::forget()不会返回true / false。您只需删除if声明即可。

作为旁注,如果您仅使用user中的Session键来存储当前登录的用户,则可以改为使用Auth::user()

答案 3 :(得分:0)

您可以使用包含当前会话的Request参数。这样您就可以通过键删除任何会话值:

use Illuminate\Http\Request;

Route::get('/logout', function(Request $request) {
        //Uncomment to see the logs record
        //\Log::info("Session before: ".print_r($request->session()->all(), true));
        if ($request->session()->has('key')) {
           $request->session()->forget('key');
        }
        //Uncomment to see the logs record
        //\Log::info("Session after: ".print_r($request->session()->all(), true));
        return redirect('/');
    });

或者您可以删除会话中的所有值:

use Illuminate\Http\Request;

Route::get('/logout', function(Request $request) {
        //Uncomment to see the logs record
        //\Log::info("Session before: ".print_r($request->session()->all(), true));
        $request->session()->flush();
        //Uncomment to see the logs record
        //\Log::info("Session after: ".print_r($request->session()->all(), true));
        return redirect('/');
    });

参考:https://laravel.com/docs/5.3/session#using-the-session

答案 4 :(得分:0)

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    use App\Http\Controllers\Controller;

    class StudentRecord extends Controller
       {

    public function logout(Request $req)
        {
     if($req-session()->has('key'){
              $req->session()->forget('key');
        return redirect('/');
              }

//Or simple
    public function logout(Request $req)
        {
     //if($req-session()->has('key')
         $req->session()->flush();
         }


    }


    //Then Do this in your route file
      Route:get("/logout",StudentRecord@logout);

        <a href=" {{ url(logout)}}">logout</a>