I would like to create helper functions to avoid repeating code between views in Laravel 5:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
They're basically text formatting functions. Where and how can I create a file with these functions?
This is my HelpersProvider.php file:
You should create a folder called
Helpers
under theapp
folder, then create file calledwhatever.php
inside and add the stringwhatever
inside the $helpers array.Done!
Edit
I'm no longer using this option, I'm currently using composer to load static files like helpers.
You can add the helpers directly at:
In laravel 5.3 and above, the laravel team moved all procedural files (
routes.php
) out of theapp/
directory, and the entireapp/
folder ispsr-4
autoloaded. The accepted answer will work in this case but it doesn't feel right to me.So what I did was I created a
helpers/
directory at the root of my project and put the helper files inside of that, and in mycomposer.json
file I did this:This way my
app/
directory is still a psr-4 autoloaded one, and the helpers are a little better organized.Hope this helps someone.
in dir bootstrap\autoload.php
add this file
This is what is suggested by
JeffreyWay
in this Laracasts Discussion.app/Http
directory, create ahelpers.php
file and add your functions.composer.json
, in theautoload
block, add"files": ["app/Http/helpers.php"]
.composer dump-autoload
.Create a
helpers.php
file in your app folder and load it up with composer:After adding that to your
composer.json
file, run the following command:If you don't like keeping your
helpers.php
file in yourapp
directory (because it's not a PSR-4 namespaced class file), you can do what thelaravel.com
website does: store thehelpers.php
in the bootstrap directory. Remember to set it in yourcomposer.json
file:Another Way that I used was: 1) created a file in app\FolderName\fileName.php and had this code inside it i.e
2) After that in our blade
that's it. and it works