Saturday, November 16, 2019

Best Practices for Custom Helpers in Laravel 5

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

Custom Classes in Laravel 5, the Easy Way

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!!');
    }
    ...
https://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-in-laravel-5

No comments:

Post a Comment