Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Global Helpers: Last Resort

Premium
4 min read

This lesson is the last part of the section about the app/ folder structure. What if you have some methods for transforming data but don't know where to place them, as they may be used in various places?

The most flexible "last resort" is to create global helpers.

Helper classes have been around for a while. It's any Class with some helper methods related to some topic, like DateHelper or CurrencyHelper.

For example, earlier, we created the Attribute startAt() in the User model, which has some data manipulation that can be added to a helper.

Model:

protected function startAt(): Attribute
{
return Attribute::make(
set: fn ($value) => Carbon::createFromFormat('m/d/Y', $value)->format('Y-m-d');
)
}

Create a new file app/Helpers/DateHelper.php (there's no Artisan command for this), and inside the DateHelper class, add the convertToDB() method, which will have the code from the attribute.

namespace App\Helpers;
 
class DateHelper
{
public static function convertToDB($date)
{
return Carbon::createFromFormat('m/d/Y', $date)->format('Y-m-d');
}
}

Now you can change Attribute to use this helper:

protected function startAt(): Attribute
{
return Attribute::make(
set: fn ($value) => DateHelper::convertToDB($value);
)
}

Now, you can just use this helper whenever you need to...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…