Toufik94's avatar

Laravels intended() function not working at all

Hi guys,

Some time ago I implemented a custom login following Laravel's documentation. This is what it looks like currently:


namespace App\Http\Controllers;

use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Mockery\Generator\StringManipulation\Pass\Pass;

class AuthController extends Controller
{
    public function index()
    {
        return view('auth.login');
    }

    public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $remember = $request->remember;

        if (Auth::attempt($credentials, $remember)) {
            $request->session()->regenerate();

            return redirect()->intended('/home');
        }

        return back()->withErrors([
            'status' => 'Uw gebruikersnaam en/of wachtwoord zijn onjuist.',
        ]);
    }

    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();
    }

    public function showPasswordRequestForm() {
        return view('auth.forgot-password');
    }

    public function sendPasswordResetMail(Request $request): \Illuminate\Http\RedirectResponse
    {

        $request->validate(['email' => 'required|email']);

        $status = Password::sendResetLink(
            $request->only('email')
        );

        return $status === Password::RESET_LINK_SENT
            ? back()->with(['status' => __($status, ['email' => $request->email])])
            : back()->withErrors(['email' => __($status)]);
    }

    public function showPasswordResetForm($token) {

        $email =  request()->query('email');
        $user = Password::broker()->getUser(['email' => $email, 'token' => $token]);

        if (!Password::broker()->tokenExists($user, $token)) {
            return redirect()->route('password.request')
                ->withErrors(['email' => 'De link in uw e-mail is verlopen.
                Vul uw mailadres hieronder in om een nieuwe link te ontvangen.
                Let op: deze link is 60 minuten geldig.']);
        }

         return view('auth.reset-password')->with('token', $token);
    }

    public function resetPassword(Request $request): \Illuminate\Http\RedirectResponse
    {
            $request->validate([
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:8|confirmed',
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function ($user, $password) {
                $user->forceFill([
                    'password' => Hash::make($password)
                ])->setRememberToken(Str::random(60));

                $user->save();

                event(new PasswordReset($user));
            }
        );

        return $status === Password::PASSWORD_RESET
            ? redirect()->route('login')->with('status', __($status))
            : back()->withErrors(['email' => [__($status)]]);
    }
}

No issues with logging in at all. What i've added recently is this part inside the authenticate-method:

return redirected()->intended('/home')

This should normally ensure that the user, after logging in, gets back to the page that it intended to visit after the auth middleware intercepted the request. However, this is not the case. I'm always being redirected to the '/home' route which is also the RouteServiceProvider HOME variable.

What am I doing wrong? I've created multiple test routes which all have the Auth-middleware assigned to it, but it always gives me the same result.

0 likes
10 replies
tykus's avatar

You don't return, so the instead you return back instead.

if (Auth::attempt($credentials, $remember)) {
    $request->session()->regenerate();

    return redirect()->intended('/home');
}
Toufik94's avatar

@tykus That was a small mistake of me, but it still didn't change anything. Still the same result.

Toufik94's avatar

Update: I managed to make it work, but only when changing the RedirectIfAuthenticated middleware.


namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return redirect()->intended(RouteServiceProvider::HOME);
            }
        }

        return $next($request);
    }
} 

I changed this

return redirect(RouteServiceProvider::HOME)

into this

return redirect()->intended(RouteServiceProvider::HOME)

But it's weird why it didn't work when I made the change in my AuthController. I did exactly the same thing as the Laravel docs told me to do.

Snapey's avatar

This middleware should not even be part of the conversation. Its (default) purpose is to send authenticated users away from login and register routes.

When logging in its only purpose is to make sure logged in users cannot login.

Toufik94's avatar

@Snapey Exactly my thought. I don't like this ''solution'' but it works.

I really wonder why the code in the OP doesnt work.

Snapey's avatar

@Toufik94 Your original post does not contain the code you are trying, and we don't know by what method you reached the controller.

Toufik94's avatar

@Snapey What do you mean? The OP contains the full controller and it's the authenticate() method that I tried. I even highlighted which code fragment is causing me problems.

Snapey's avatar

so what route were you visiting when the login page got inserted?

Toufik94's avatar

@Snapey I had a test route called /projects that has the auth middleware assigned to it. I tried visiting that route by going to localhost:8000/projects. The auth middleware intercepted the request as expected and redirected me to /login. I tried loggin in with success but the application send me straight to /home instead of /projects.

Toufik94's avatar

Anyone? This problem is really frustrating. I don't get what Im doing wrong.

It seems like every form of redirecting isn't possible in my AuthController. The redirect by the RedirectIfAuthenticated middleware is always overruling the redirects in the AuthController when logging in.

Please or to participate in this conversation.