Only until March 18th: coupon LARAVEL12 for 40% off Yearly/Lifetime membership!

Read more here
Courses

How to Structure Laravel 11 Projects

Global Helpers: Last Resort

Summary of this lesson:
- Creating helper classes for common functions
- Implementing static helper methods
- Managing global utility functions
- Organizing helper structure

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 11 lessons of this course? (56 min read)

You also get:

  • 71 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord