We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to run function beforeExecuteRoute 1 times. beforeExecuteRoute loop continuously, how to make it redirect only once

public function beforeExecuteRoute()
{
    if (!$this->getCustomer()) {
        $this->response->redirect("/login");
    }

}
public function beforeExecuteRoute()
{
    if (!$this->getCustomer()) {
        if($this->dispatcher->getControllerName() != 'auth' && $this->dispatcher->getActionName() != 'login') {
            $this->response->redirect("/login");
        }
    }

}


8.4k
edited Apr '20

you have to provide more information like where is beforeExecuteRoute in a controller or a extended class ?

because if this method in a controllerbase for instance it will be executed for each controller gets initiated

so i think the short answer for this you have to return false after the redirect to stop the execution

beforeExecuteRoute is an event that can be stopped check the documentation here

public function beforeExecuteRoute()
{
    if (!$this->getCustomer()) {

        $this->response->redirect("/login");

        return false;
    }
}

@Lajos' solution should work. What's happening is every time a route is executed, you're redirecting. That includes the route for the login page. If you wrap your redirection in a condition that fails on the login page, then the redirection won't happen on that page.