I would like to create helper functions to avoid repeating code between views in Laravel 5:
view.blade.php
Foo Formated text: {{ fo
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
instead of including your custom helper class, you can actually add to your config/app.php
file under aliases.
should be look like this.
'aliases' => [
...
...
'Helper' => App\Http\Services\Helper::class,
]
and then to your Controller, include the Helper using the method 'use Helper' so you can simply call some of the method on your Helper class.
eg. Helper::some_function();
or in resources view you can directly call the Helper class already.
eg. {{Helper::foo()}}
But this is still the developer coding style approach to be followed. We may have different way of solving problems, and i just want to share what i have too for beginners.
Create Helpers.php in app/Helper/Helpers.php
namespace App\Helper
class Helpers
{
}
Add in composer and composer update
"autoload": {
"classmap": [
"database/seeds",
"database/factories",
"database","app/Helper/Helpers.php"
],
"psr-4": {
"App\\": "app/"
},
"files": ["app/Helper/Helpers.php"]
},
use in Controller
use App\Helper\Helpers
use in view change in config->app.php file
'aliases' => [
...
'Helpers' => 'App\Helper\Helpers'
],
call in view
<?php echo Helpers::function_name(); ?>
Create custom helpers’ directory: First create Helpers directory in app directory. Create hlper class definition: Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code
<?php
namespace App\Helpers;
class MyFuncs {
public static function full_name($first_name,$last_name) {
return $first_name . ', '. $last_name;
}
}
namespace App\Helpers; defines the Helpers namespace under App namespace. class MyFuncs {…} defines the helper class MyFuncs. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string
Helpers service provide class
Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.
Run the following artisan command:
php artisan make:provider HelperServiceProvider
The file will be created in /app/Providers/HelperServiceProvider.php
Open /app/Providers/HelperServiceProvider.php
Add the following code:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
require_once($filename);
}
}
}
HERE,
namespace App\Providers; defines the namespace provider
use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
public function boot(){…} bootstraps the application service
public function register(){…} is the function that loads the helpers
foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.
We now need to register the HelperServiceProvider and create an alias for our helpers.
Open /config/app.php
file
Locate the providers array variable
Add the following line
App\Providers\HelperServiceProvider::class,
Locate the aliases array variable
Add the following line
'MyFuncs' => App\Helpers\MyFuncs::class,
Save the changes Using our custom helper
We will create a route that will call our custom helper function Open /app/routes.php
Add the following route definition
Route::get('/func', function () {
return MyFuncs::full_name("John","Doe");
});
HERE,
return MyFuncs::full_name("John","Doe"); calls the static function full_name in MyFuncs class
Best Practice to write custom helpers is
1) Inside the app
directory of the project root, create a folder named Helpers (Just to separate and structure the code).
2) Inside the folder write psr-4 files or normal php files
If the PHP files are in the format of psr-4 then it will be auto loaded, else add the following line in the composer.json which is inside the project root directory
Inside the autoload
key, create a new key named files
to load files at the time of auto load,inside the files
object add the path starting from app directory., here is an example.
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/customHelpers.php"
]
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
},
PS : try running composer dump-autoload
if the file dosen't loaded.
In laravel 5.3 and above, the laravel team moved all procedural files (routes.php
) out of the app/
directory, and the entire app/
folder is psr-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 my composer.json
file I did this:
...
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"helpers/ui_helpers.php"
]
},
...
This way my app/
directory is still a psr-4 autoloaded one, and the helpers are a little better organized.
Hope this helps someone.