So, I managed to make it working using the code from @luceos and the addition of @clarkwinkelmann and a small edit. Thank you guys! ๐ป
Here's the working code:
(new Extend\Event)
// Add a user to a specific group after number of approved posts, requires flarum/approval.
->listen(\Flarum\Post\Event\Posted::class, function (\Flarum\Post\Event\Posted $event) {
$needsApprovedPosts = 2; // number of approved posts to add group to user
$addGroup = 6; // use the Id of the group you want to add
$adminGroup = 1;
$modGroup = 4;
$user = $event->post->user;
// Skip if user is already part of group
if ($user->groups->find($addGroup) !== null) return;
if ($user->groups->find($adminGroup) !== null) return;
if ($user->groups->find($modGroup) !== null) return;
if ($user->posts()
->where('is_approved', 1)
->whereNull('hidden_at')
->count() >= $needsApprovedPosts) {
$user->groups()->attach($addGroup);
}
}),
The slight difference with the original code @luceos suggested is that ->where('is_approved')
doesn't work and needs to be replaced with ->where('is_approved', 1)
, I guess the Laravel framework doesn't automatically interpret the int as boolean.
Please let me know if there's a better way to check whether the user groups match any of the three given ones, I couldn't make it working with a single find() statement and an array of ID-s and I'm not sure if three separate find() statements are the optimal way but I'm a Java devloper and I've used SQL more than 10 years ago, so really guessing here.