I am on laravel mysql and I want a percentage and number of how many new users have been created or left in the past 30 days.
For example, if there are 3 users before 30 days and 2 new users have been created between 30 days so, according to my calculation it should be ((2-3)/3) *100 = -33.33. I don’t know how to get the right percentage. and also if the left users are more then before 30 days users, then it should be shown in red color. I don’t know how to differentiate between positive percentages and negative percentages.
I have atteched the screenshort of what i actully want.
I tried this code but i am not 100% sure about the output.
$currentDate = Carbon::now();
$startDate = now()->subDays(30)->startOfDay();
$startDate = Carbon::now()->subDays(30);
$totalUsers = User::count();
$createdUsers = User::where('created_at', '>=', $startDate)->count();
$number = (($createdUsers - $totalUsers) / $totalUsers+1) * 100;
2
Answers
To calculate the percentage and number of new users created or left in the past 30 days, you can use the following steps:
Get the count of users before 30 days:
Get the count of new users created in the past 30 days:
Calculate the percentage difference:
Determine the color based on the percentage difference:
You can then use the $percentageDifference and $color variables to display the result accordingly in your Laravel view.
Here’s an example of how you can implement this in a Laravel view:
I’ve tried walking through this with your example numbers, but I do not understand how an increase of users can result in a negative growth value (-33.33%).
The only ways I can imagine you wanting a negative value are:
Perhaps you do just want to look at the total number of users, relative to 30 days ago. In which case, here’s a walk-through, and suggested code that might achieve that.
Say you had 3 users before, and an additional 2 users in the past 30 days.
I assume for that, the absolute number of new users you want is 2, and the percentage you want is 66.67%, because 3 + 2 = 5, and 5 is ~1.67 times your original number, or an increase of ~66.67%.
so your code would result in 40, which is seemingly not the desired result.
Instead, you could do: