How to create functions available globally in laravel?

1

I would like to create functions that are globally available to reuse the code.

What would be the best way to do this, in laravel ...

The flow I need would be like this:

I will receive a "Route" request

  

Then I'll process > "Controler" in this case I will have to do several processing so I thought about doing several functions that can be used, in case I will use third party API for processing too.   then I'll pass display using > "View Blade".

Any ideas will be welcome ...

    
asked by anonymous 02.01.2019 / 00:12

1 answer

2

What you are looking for is probably an Auxili class, a Helper class.

1 - Create a file in the /App/Helpers/Helper.php path

<?php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

2 - Add a nickname, Alias, to the config / app.php file

<?php

'aliases' => [
 ...
    'Helper' => App\Helpers\Helper::class,
 ...

3 - Use in views

{!! Helper::shout('exemplo de uso de helper!!') !!}

4 - Use in any controller or other places:

<?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 in English

    
03.01.2019 / 01:53