CodeIgniter Forums
Customize the redirect if not logged in - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Addins (https://forum.codeigniter.com/forumdisplay.php?fid=34)
+--- Thread: Customize the redirect if not logged in (/showthread.php?tid=86270)



Customize the redirect if not logged in - groovebird - 01-25-2023

Hi,

if the user is not logged in and calls a protected route then the redirect goes to the /login route. How can i change this route to a custom url?

Doing a check with

PHP Code:
if auth()->loggedIn() { //go to custom url} 

does not work in the controller. The redirect goes always to the /login route

I found the solution in the documentation by using a filter:

PHP Code:
class LoggedIn implements FilterInterface
{
    public function 
before(RequestInterface $request$arguments null)
    {

        if (!
auth()->loggedIn()) {
            return 
redirect()->to(site_url('mycustomurl'));
        }
    }

    public function 
after(RequestInterface $requestResponseInterface $response$arguments null)
    {

    }




RE: Customize the redirect if not logged in - [email protected] - 04-03-2023

Hi,
change the redirects in auth.php config:


PHP Code:
auth.php:
    /**
    * --------------------------------------------------------------------
    * Redirect URLs
    * --------------------------------------------------------------------
    * The default URL that a user will be redirected to after various auth
    * auth actions. This can be either of the following:
    *
    * 1. An absolute URL. E.g. http://example.com OR https://example.com
    * 2. A named route that can be accessed using `route_to()` or `url_to()`
    * 3. A URI path within the application. e.g 'admin', 'login', 'expath'
    *
    * If you need more flexibility you can override the `getUrl()` method
    * to apply any logic you may need.
    */
    public array $redirects = [
        'register'    => '/',
        'login'      => '/',
        'logout'      => 'login',
        'force_reset' => '/',
    ];