/    Sign up×
Bounties /Pin to ProfileBookmark

Best practices for Helper functions in Laravel?

What are the best practices for Helper functions in Laravel? I’ve found a few answers, but they differ in where the file is stored and how the functions are then accessed. Is there a one-size-fits-all solution? My goal is to have a text-processing function that I can then use across multiple of Laravel’s blade files.

to post a answer
Laravel

1 Replies

Copy linkTweet thisAlerts:
@AndrewBentleyAug 11.2022 — In my opinion this is best done in the following way:
First create a helper class by creating a folder called Helpers in the app directory of Laravel and then create a file in it with a naming you'd like, I chose MyTextDecorator for your case:
namespace App\Helpers;

class MyTextDecorator
{
static function myText($inputText)
{
// add any logic or processing you'd like to do to the text here
$result = "I like " . $inputText . "!";
return $result;
}
}


Then make sure to alias your class in config\app.php in the aliases array:
'aliases' => [
// Other aliases
'MyTextDecorator' => App\Helpers\MyTextDecorator::class
]
and then you will be able to use the output in your blade files:

{!! MyTextDecorator::myText('apples') !!}
It should output: I like apples!
×

Success!

Help @XavierConley spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...