Laravel fails to redirect when specifying URL - laravel-5

I want Laravel to redirect to '/dashboard' instead, Laravel keeps taking me to '/' after login.
LoginController.php
public function redirectPath()
{
return '/dasboard';
}
Middleware
if (Auth::guard($guard)->check())
{
return redirect()->intended('/dashboard');
}

protected function authenticated()
{
return redirect('/home');
}

Related

Redirect from web routes using can

By default on using can if not authorized, an exception is thrown. I want to redirect instead of showing this exception.
web.php
Route::group(['middleware' => 'auth'], function(){
Route::get('/users', [userController::class, 'index'])->can('view', 'user');
});
The exception is executed from response.php:
public function authorize()
{
if ($this->denied()) {
throw (new AuthorizationException($this->message(), $this->code()))
->setResponse($this);
}
return $this;
}
I tried to redirect from there but it's not working:
public function authorize()
{
if ($this->denied()) {
return redirect('/');
}
return $this;
}
UserPolicy.php:
public function view(User $user)
{
return $user->hasPermission('user-view');
}
is it possible to redirect instead of throwing this exception or I have to check from the controller and redirect from there?

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')

how to remove this error in laravel middleware?

I am trying to using middleware in laravel but it is giving this error
"The page isn’t redirecting properly"
i have done this
IsAdmin(middleware)
public function handle($request, Closure $next)
{
$user=Auth::user();
if($user->isAdmin())
{
return redirect()->intended('/admin');
}
return $next($request);
}
}
admin controller
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('IsAdmin');
}
public function index()
{
return "You are an administrator because you are seeing this page";
}
}
User Model
public function isAdmin()
{
if($this->role->name=='administrator')
{
return true;
}
return false;
}
web.php
Route::get('/admin','AdminController#index');
"The page isn’t redirecting properly"
Try changing return $next($request); to return redirect()->back();, it might be infinite redirect loop, because you are still trying to access the same route even if middleware fails.

Laravel 5.4 Route [login] not defined

Hi I have following route and constructor in my controller i want to check if user is authenticated or not if not then redirect to /warehouse/login page. but for some reasons i am getting Route [login] not defined error.
I am migrating my functions from Laravel 4.2 to Laravel 5.4
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if (!Auth::check()) {
$url = URL::current();
$routeName = Route::currentRouteName();
if ($routeName != "AdminLogin" && $routeName != 'admin') {
Session::put('pre_admin_login_url', $url);
}
return redirect('/warehouse/login');
}
return $next($request);
}, array('except' => array('WarehouseAdminLogin', 'WarehouseAdminVerify')));
}
Routes:
Route::get('/warehouse', 'WarehouseController#index');
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
You didnt define your login function.
make a function
public function login()
{'your code'}
in your WarehouseController
Edited: the problem is that you have not a route named login. This error is caused by:
$this->middleware('auth');
because this code in the auth middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
So what to do is remove auth middleware and try again or make a route with login name.

Laravel After Logging in is going to / Route

This is mine LoginController
protected $redirectTo;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
if(Auth::check() && Auth::user()->role->id == 1){
$this->redirectTo=route('admin.dashboard');
}
else{
$this->redirectTo=route('user.dashboard');
}
$this->middleware('guest')->except('logout');
}
}
Here is mine web.php
Route::get('/', function () {
return view('welcome');
})->name('home');
Auth::routes();
I don't know Why after Successfully logging in its going to / route i want to send it to another route which after logging in i manually Enter the route i successfully viewed that route if i am logged in its not going to show but how can i manage after logging in route
You are doing it wrong. You shouldn't put such code into controller constructor because it won't probably work.
Instead in your controller you should define custom redirectTo method:
protected function redirectTo()
{
if(Auth::check() && Auth::user()->role->id == 1) {
return route('admin.dashboard');
}
return $this->redirectTo=route('user.dashboard');
}
This should work because in Illuminate/Foundation/Auth/RedirectsUsers.php trait there is method:
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
defined that is used later in LoginController by default when user was succesfully logged.

Resources