drupal 8 redirect different roles to different pages on login
From https://drupal.stackexchange.com/a/223380/4195 and https://stackoverflow.com/a/49556334/1028376 we combined things to get this:
use Drupal\Core\Url;
use Drupal\user\UserInterface;
/**
* Implements hook_user_login().
*/
function drutopia_findit_service_provider_user_login(UserInterface $account) {
// Only do this for Service Providers.
$roles = $account->getRoles();
if (!in_array('serviceprovider', $roles)) {
return;
}
// Ignore password reset.
$route_name = \Drupal::routeMatch()->getRouteName();
if ($route_name !== 'user.reset.login') {
// Do not interfere if a destination was already set.
$current_request = \Drupal::service('request_stack')->getCurrentRequest();
if (!$current_request->query->get('destination')) {
// Default login destination to the service provider dashboard.
$current_request->query->set(
'destination',
Url::fromRoute('view.opportunities.page_1')->toString()
);
}
}
}