Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Best Practices for Custom Helpers in Laravel 5

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?
by

2 Answers

Bharatgxwzm
Custom Classes in Laravel 5, the Easy Way
This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer.

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!!');
}
...
sandhya6gczb
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:

Login / Signup to Answer the Question.