I am trying to remove a basic session but it's not removing. Here's the code
welcome.blade.php
@if(Session::has('key'))
{{ Session::get('key')}}
<a href="logout">Sign Out</a>
@else
please signin
@endif
</div>
I don't know how to remove session. Here's the one I used but it's not working route.php
Route::get('/logout', function() {
$vv = Session::forget('key');
if($vv)
{
return "signout";
}
});
You should use this method
Route::get('/logout', function() {
Session::forget('key');
if(!Session::has('key'))
{
return "signout";
}
});
You can try with Session::pull('key');
And if you want to delete all sessions variable you can use Session::flush();
http://laravel.com/docs/5.0/session#session-usage
Session::forget()
does not return true/false. You can just remove your if
statement.
As a side note, if you're only using the user
key in Session
for storing the currently logged in user, you can just use Auth::user()
instead.
You can use the Request
parameter, containing the current session. This way you can delete any session value by the key:
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('/');
});
Or you can delete all values in the session:
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('/');
});
Reference: https://laravel.com/docs/5.3/session#using-the-session
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>