Ad

How To Redirect From Event Handler In OctoberCMS Plugin?

- 1 answer

I have registered a listener for 'rainlab.user.logout' in the boot event of my plugin.

public function boot()
{
    Event::listen('rainlab.user.logout', function ($controller) {
        return Redirect::to('https://www.google.com');
    });
}

It does nothing. I have confirmed the flow is reaching this block by using

header("Location: https://www.google.com");
exit;

in place of the return statement which gives an alert box saying "error" without the redirect.

Ad

Answer

You can use Logout Ajax link's data attribute to redirect anywhere you want. check below example. [ for this to work you need to add session component to your page ]

check for more info : https://octobercms.com/plugin/rainlab-user#documentation

<a data-request="onLogout" 
   data-request-data="redirect: 'https://www.google.com'"
>
   Sign out
</a>

Still if you want to use event to redirect user you can use below code. Note : its kind of hacky approach not recommended but yes it works.

Event::listen('rainlab.user.logout', function ($controller) {
  $_POST['redirect'] = 'https://www.google.com';        
});

Why your approach is not working [ Extra for understanding only ]

Because in event handler they did not catch any data which you return from event, you are returning Redirect but in handler they don't catch it or receive it, this event rainlab.user.logout just fired and let you access $user object data nothing more. so your return statement has no effect on it.

content : plugins/rainlab/user/components/Session.php

public function onLogout()
{
    $user = Auth::getUser();

    Auth::logout();

    if ($user) {
        Event::fire('rainlab.user.logout', [$user]);
        // ^ see, nothing is here which can accept your return redirect.
    }

    $url = post('redirect', Request::fullUrl());

    Flash::success(Lang::get('rainlab.user::lang.session.logout'));

    return Redirect::to($url);
}

if you have any doubt please comment.

Ad
source: stackoverflow.com
Ad