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...