0

I am working on a multilingual laravel site with many public pages.

Currently, when you log in you are redirected to the homepage in the main language. We need to redirect the user to same page, or a level higher.

I figured out how to send a returnUri and process it in the LoginController. After login the user is now send to the homepage in the user-chosen language. But not to the original page.

I have this code:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use LaravelLocalization;

class LoginController extends Controller {

    use AuthenticatesUsers {
        logout as performLogout;
    }

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'https://localhost:3080/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Request $request) {
        switch (LaravelLocalization::getCurrentLocale()) {
            case 'nl':
                $locale = 'nl';
                break;
            default:
                // only some pages are in swedish
                $locale = 'en';
                break;
        }

        var $returnUrl = '';
        if ($request->has('returnUrl')) {
            $returnUrl = "/".$request->returnUrl;
        }

        $this->redirectTo.= $locale.$returnUrl;
//        dd('logging', $this->redirectTo);

        $this->middleware('guest', ['except' => 'logout']);
    }

    public function logout(Request $request) {
        $this->performLogout($request);

        return redirect()->route('login');
    }
}

I tried to make a login function similar to the logout function but that would cause too many redirects.

I saw the RedirectIfAuthenticated handler, but I don’t see how it could take different uris.

1 Answers1

1

You could use Laravel's intended() function. This redirects the user to the intended page after login.

return redirect()->intended('fallback-url');

The intended method on the redirector will redirect the user to the URL they were attempting to access before being caught by the authentication filter. A fallback URI may be given to this method in case the intended destination is not available.

Source: Laravel docs

luukd
  • 356
  • 8