I would like to create helper functions to avoid repeating code between views in Laravel. For example:
view.blade.php
<p>Foo Formated text: {{ fooFormatText($text) }}</p>
They're basically text formatting functions. How should I define globally available helper functions like fooFormatText()
?
In this file, you can write our own functions and call anywhere in your laravel based project. Go to App directory and create a new file new helpers.php like this app/helpers.php. 2. Add File Path In composer.json File In this second step, you will add the path of the helpers file in the composer.json file.
Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method: <?php // Code within app\Helpers\Helper.php namespace App\Helpers; class Helper { public static function shout (string $string) { return strtoupper ($string); } } <?php // Code within config/app.php 'aliases' => [ ...
Composer is supposed to be a tool to include libraries: Laravel would work perfectly well without it, and Composer without Laravel. This suggestion tells us to create a file within our app, leave our app, go to Composer, tell composer to go back into our app and include a file. Laravel clearly handles the inclusion of files, right?
Laravel uses composer's autoloader to know where to include all the libraries and files it relies on. This referenced in bootstrap/autoload.php. Read the comment in that file. The approach is to add the reference to the file into the composer.json, then "dump autoload," which regenerates composer's autoloader so that Laravel can find it.
Create a helpers.php
file in your app folder and load it up with composer:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},
After adding that to your composer.json
file, run the following command:
composer dump-autoload
If you don't like keeping your helpers.php
file in your app
directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com
website does: store the helpers.php
in the bootstrap directory. Remember to set it in your composer.json
file:
"files": [
"bootstrap/helpers.php"
]
This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.
Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:
<?php // Code within app\Helpers\Helper.php
namespace App\Helpers;
class Helper
{
public static function shout(string $string)
{
return strtoupper($string);
}
}
Step 2: Create an alias:
<?php // Code within config/app.php
'aliases' => [
...
'Helper' => App\Helpers\Helper::class,
...
Step 3: Run composer dump-autoload
in the project root
Step 4: Use it in your Blade template:
<!-- Code within resources/views/template.blade.php -->
{!! Helper::shout('this is how to use autoloading correctly!!') !!}
Extra Credit: Use this class anywhere in your Laravel app:
<?php // Code within app/Http/Controllers/SomeController.php
namespace App\Http\Controllers;
use Helper;
class SomeController extends Controller
{
public function __construct()
{
Helper::shout('now i\'m using my helper class in a controller!!');
}
...
Source: http://www.php-fig.org/psr/psr-4/
Why it works: https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php
Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php
my initial thought was the composer autoload as well, but it didn't feel very Laravel 5ish to me. L5 makes heavy use of Service Providers, they are what bootstraps your application.
To start off I created a folder in my app
directory called Helpers
. Then within the Helpers
folder I added files for functions I wanted to add. Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable.
Next I created a HelperServiceProvider.php
by running the artisan command:
artisan make:provider HelperServiceProvider
Within the register
method I added this snippet
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
lastly register the service provider in your config/app.php
in the providers array
'providers' => [
'App\Providers\HelperServiceProvider',
]
now any file in your Helpers
directory is loaded, and ready for use.
UPDATE 2016-02-22
There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. You can either use the package for inspiration or feel free to download it with Composer as well. It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. Feedback and PRs are much appreciated!
composer require browner12/helpers
Github: browner12/helpers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With