Lravel 5.2 session::forget() and session::flush() not working - laravel-5

i have just make a sub authentication Middleware in my Laravel 5.2 application which use Laravel session to store data.
I can put my data to Laravel session
But when i want to delete that variable form session it working for only that request when page redirect or someone reload the page that variable still exists.
In My controller File
class SubmissionController extends Controller
{
public function login(Request $request){
if($request->session()->has('submission')) return redirect('/submission-directory');
return view('submission.login');
}
public function dologin(Request $request){
if(!$request->get('password') == "reader") return redirect('/submission-directory/login')->withErrors('errors.wrong-password');
Session::put('submission','yes');
$redirect = $request->session()->pull('submission_redirect','/submission-directory');
return redirect($redirect);
}
public function index(Request $request){
dump($request->session()->all());
$request->session()->forget('submission');
dump($request->session()->all());
die('coming here');
}
}
but when I reload the page You can session is still exists..
Notice :: I have put all the routs in web Middleware group
Route.php
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix'=>'/submission-directory'],function(){
Route::get('/login','submissionController#login');
Route::post('/login',['as'=>'submission.login','uses'=>'SubmissionController#doLogin']);
Route::group(['middleware'=>'submission'],function(){
Route::get('/','SubmissionController#index');
});
});

Try this
IN Controller :
use Session;
public function index(Request $request)
{
dump(Session::all());
Session::forget('submission');
print_r((Session::all());
die;
}

Related

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

Multiple update methods in same controller Laravel 6

I am currently trying to build a user registration system with edit fields. At the edit portion, I had to create separate views for editing/updating personal details, email, and passwords.
I started with an empty resource controller. it had only one edit method. Hence I added additional edit methods. Each method can have a separate route. However, I have a hard time having a separate route for each update method in each section as the resource has only one route like this in docs:
PUT/PATCH /photos/{photo} update photos.update
Is there any workaround for this?
Controller
class UserController extends Controller
{
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
public function index()
{
return view('users.index');
}
public function edit_personal(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.personal', ['users' => $user_profile]);
}
public function update_personal(Request $request, User $user)
{
// How to write route for this method.
}
public function edit_email(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.email', ['users' => $user_profile]);
}
public function update_email(Request $request, User $user)
{
// How to write route for this method.
}
public function edit_password(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.password', ['users' => $user_profile]);
}
}
Routes
Auth::routes(['verify' => true]);
Route::get('/', function () {
return view('welcome');
});
Route::get('/users/{user}/personal', 'UserController#edit_personal')->name('users.personal');
Route::get('/users/{user}/email', 'UserController#edit_email')->name('users.email');
Route::get('/users/{user}/password', 'UserController#edit_password')->name('users.password');
Route::resource('users', 'UserController');
Basically I have separated edit portion of user controller into personal, email and password sections and they have separate forms. I want to write update functions for each section in UserController.
don't know why are you using separate forms for updating each fields while you can do it in a single form. however you can use either put/patch or post method for updates. here's i am using post for example.
routes:
Route::get('users/{user}/personal', 'UserController#edit_personal')->name('users.personal');
Route::post('users/{user}/personal', 'UserController#update_personal')->name('users.update-personal');
Route::get('users/{user}/email', 'UserController#edit_email')->name('users.email');
Route::post('users/{user}/email', 'UserController#update_email')->name('users.update-email');
Route::get('users/{user}/password', 'UserController#edit_password')->name('users.password');
Route::post('users/{user}/password', 'UserController#update_password')->name('users.update-password');
as you are using route model binding you can directly get the object.
public function edit_personal(User $user)
{
return view('users.edit.personal', ['users' => $user]);
}
public function update_personal(Request $request, User $user)
{
//validation goes here
$user->update([
'value' => $request->value,
...........
]);
}

My laravel login route leads to a blank page with the same URL

My laravel route fails to go to the specified route. I have made a custom authentication page that should lead to dashboard.blade.php when a registered user logs in. But it returns a blank page with the same URL for login when a user uses wrong credentials.
This is my route list:
This is my form tag for the login form
<form method="post" action="{{route('login.store')}}">
Controller store() method:
public function store(Request $request) {
$credentials = $request->only('employeeID', 'password');
if (Auth::attempt($credentials)) {
Session::flash('login','login Successful!');
return view('dashboard');
}
}
Controller index() method:
public function index() {
return view('login');
}
This web.php source code:
Route::get('/', function () {
return view('register');
});
Route::resource('register', 'registerController');
Route::get('/login',function(){
return view('login');
});
Route::resource('login', 'loginController');
Route::get('/dashboard',function(){
return view('dashboard');
});
Route::resource('/logout', 'logoutcontroller#logout');
Route::resource('/dashboard', 'dashboardcontroller#index');
DashboardController source code:
public function index() {
return view('dashboard');
}

Laravel 5.2 - middleware auth

i just installed laravel 5.2, and i created auth register, login, and reset password, but now i want create a index of my project where all user (also not logged) can access. i tryed to create
Route::get('/',HomeController#home');
But this view is enable only for users logged.
MY ROUTES
Route::auth();
Route::get('/home', 'HomeController#index');
// POST - FORM CREA
Route::get('/crea-regalo', 'PostController#form');
Route::post('/crea-regalo', 'PostController#creaPost');
// LISTA ANNUNCI PRINCIPALE
Route::get('/', 'HomeController#home');
MY HOME CONTROLLER
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('id','DESC');
return view('home', compact('posts'));
}
public function home()
{
$posts = Post::all();
return view('index', compact('posts'));
}
}
How can i create routes of view where ALL users can access?
Thank you for your help!
Hi write separate controller to access page to all because you have written auth middleware in contructor
public function __construct()
{
$this->middleware('auth');
}
Similar like
class GuestController extends Controller
{
public function __construct()
{
}
public function home()
{
$posts = Post::all();
return view('index', compact('posts'));
}
}
In route
Route::get('/home', 'GuestController#home');
or else you can do like this
$this->middleware('auth', ['except' => ['home']]);
this will able to access home page for all .In your constructor add this
public function __construct()
{
$this->middleware('auth', ['except' => ['home']]);
}
Put those route which you want to allow only authenticated user in middleware auth as follows:
Route::group(['middleware' => ['auth']], function () {
//your routes
})
And for those routes which all user can access put that out side the above group.

Laravel route group middleware issue

I keep some laravel routes in the middleware auth group as:
Route::group(['middleware'=>'auth'],function(){
Route::controller('Activities', 'ActivitiesController');
Route::get('foo','FooController#getFoo');
.....
});
When I try to login to access these page, I am unable to login and url redirect to login page again and again. But If I use constructor as:
public function __construct()
{
$this->middleware('auth');
}
In those controllers It works perfectly. What is route group problem?
Route has a ::middleware class that you can use:
Routes > web.php
Route::middleware(['auth'])->group(function(){
Route::get('/activities', 'ActivitiesController#index');
});
You can also use Route::resource(); which I prefer. If you don't know what it does, here are the docs: https://laravel.com/docs/5.8/controllers#resource-controllers
This works for me , in route
Route::group(['middleware'=>'auth'],function(){
Route::controller('activities', 'ActivitiesController');
});
then controller
<?php namespace App\Http\Controllers;
class ActivitiesController extends Controller {
public function getIndex() {
return 'you are in;
}
}
on attempt to visit /activities I was redirected to login page , and on success back to \activities with 'you are in'.
In web.php:
$roleGeneral = role1.'~'.role2.'~'.role3.'~'.role4;
Route::group(['middleware' => ['permission.role:'.$roleGeneral]], function() {})
In Kernel.php:
protected $routeMiddleware = [...,
'permission.role' => \App\Http\Middleware\CheckPermission::class,
];
In CheckPermission.php:
public function handle($request, Closure $next, $role)
{
$roleArr = explode('~', $role);
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$roleLogin = SysRoleModel::where('id', $user->role_id)->first();
if (in_array($roleLogin['name'], $roleArr)){
return $next($request);
}else{
return \Redirect::back()->withMessage('You are not authorized to access!');
}
}

Resources