11

I have created class Helper with path App\Http\Helpers\:

<?php

namespace App\Http\Helpers;

class Helper 
{
    public static function applyClass($user) {
        return "new";
    }

}

Then I have registered it in app.php in section aliases:

'Helper' =>   App\Http\Helpers\Helper::class

When I tried to call static method from blade:

<tr class="{{ \Helper::applyClass($user) }}">
<tr class="{{ Helper::applyClass($user) }}">

I get an error:

Class 'Helper' not found
6
  • 1
    try composer dump-autoload
    – dparoli
    Aug 19, 2019 at 16:00
  • 1
    take a look at blade service injection laravel.com/docs/master/blade#service-injection Aug 19, 2019 at 16:02
  • 1
    Injection is not required when calling static methods.
    – Namoshek
    Aug 19, 2019 at 16:03
  • I tried: composer dump-autoload no result
    – user3573738
    Aug 19, 2019 at 16:06
  • Sorry, took me a bit to write everything down. :)
    – Namoshek
    Aug 19, 2019 at 16:21

3 Answers 3

27

This is not how facades work. A custom facade is required to extend Illuminate\Support\Facades\Facade, which basically only requires the custom facade to implement protected static function getFacadeAccessor(). This method should return the name (or a class or an interface) which is supposed to be resolved by the facade.

A facade allows you to call instance methods (i.e. non-static methods) in a static way. This works because facades know how to redirect calls to static methods to the instance behind the facade. This is done by implementing __callStatic($method, $args), which simply redirects the static method call to the implementation of which the name is returned by getFacadeAccessor().

Imagine you have a service registered under the name helper in the service container. You could then execute a method getColor() on it using app('helper')->getColor() or app()->make('helper')->getColor().

With a facade called Helper which resolves your helper by returning it as string from the getFacadeAccessor() method, you can then perform the same action using Helper::getColor().


In your case, you have a few options now:

1) Using a class with static methods:

Similarly to what you already did, you can define a class with static methods. You then call these methods statically from your blade view by using the fully qualified class name (FQCN):

// app/Helpers/Helper.php
class Helper
{
    public static function getColor(): string
    {
        return 'blue';
    }
}

// resources/views/some/page.blade.php
<div style="color:{{ \App\Helpers\Helper::getColor() }}"> ... </div>

2) Using a non-static class with a facade:

You can use a similar class as above with non-static methods and add a facade for it:

// app/Helpers/Helper.php
class Helper
{
    public function getColor(): string
    {
        return 'blue';
    }
}

// app/Facades/Helper.php
class Helper extends \Illuminate\Support\Facades\Facade
{
    protected static function getFacadeAccessor()
    {
        return \App\Helpers\Helper::class;
    }
}

// config/app.php -> 'aliases' array
[
    // ... other facades ...
    'Helper' => \App\Facades\Helper::class,
]

// resources/views/some/page.blade.php
<div style="color:{{ \Helper::getColor() }}"> ... </div>

3) Using a global non-class helper file:

You can also define a basic PHP file containing some helper functions, which are registered globally. These functions are not class methods and do therefore not require being called with a class prefix:

// app/Helpers/color_utils.php
if (!function_exists('get_color')) {
    function get_color()
    {
        return 'blue';
    }
}

// app/Providers/HelperServiceProvider.php
class HelperServiceProvider extends \Illuminate\Support\ServiceProvider
{
    public function register(): void
    {
        $filenames = glob(app_path('Helpers/*.php'));

        if ($filenames !== false && is_iterable($filenames)) {
            foreach ($filenames as $filename) {
                require_once $filename;
            }
        }
    }
}

// config/app.php -> 'providers' array
[
    // ... other providers ...
    \App\Providers\HelperServiceProvider::class,
]

// resources/views/some/page.blade.php
<div style="color:{{ get_color() }}"> ... </div>

4) Using a class and service injection:

Also a nice option is to inject a service into a Blade template using the service container. Laravel provides a Blade directive called @inject($var, $fqdn) for it.

// app/Helpers/Helper.php
class Helper
{
    public static function getColor(): string
    {
        return 'blue';
    }
}

// resources/views/some/page.blade.php
@inject('helper', \App\Helpers\Helper::class)

<div style="color:{{ $helper->getColor() }}"> ... </div>

I hope the code speaks for itself. Namespaces of the files are omitted on purpose, of course you should use the namespaces according to the directories (PSR-4 compliant).

If you don't need any dependencies and you basically only need static access to something, I personally prefer global helpers (option 3).

5
  • 2
    This is The Answer, good explanation, it should be accepted blindfolded. I am missing a double upvote.
    – dparoli
    Aug 19, 2019 at 17:02
  • Yes, "this is not how facades work" but OP was not trying to create a facade, just a class alias. Their method works fine, likely they were experiencing caching issues or something. Using an alias entry is the same as setting a class alias with the use statement. The fact that most of built-in aliases are facades is just a coincidence. See for example Illuminate\Support\Str.
    – miken32
    Dec 9, 2021 at 16:32
  • 1
    Thanks for the detailed explanation. Just a note for the option 2: in Laravel 8, you will need to change the method to : protected static function getFacadeAccessor() { return \App\Helpers\Helper::class; } Feb 16, 2022 at 23:37
  • @DAMIENJIANG Good spot. In fact, it has been this way all the time and my answer was wrong. Fixed it right away, thanks.
    – Namoshek
    Feb 17, 2022 at 5:52
  • Better explained as Laravel Docs! Thanks for this approach!
    – lortschi
    Feb 8 at 11:24
7

You can achieve this in a straight forward way by following these steps.

Step 1

Create your class file in your desired path (example: app/Helpers/Helper.php) and define the class

<?php

class Helper 
{
    public static function applyClass($user) {
        return "call from helper to " . $user;
    }

}

Step 2

Modify composer.json file by adding your file within the entry of the autoload key

"autoload": {
    "prs-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/Helper.php"
    ]
}

Note that you are not changing anything apart from including this entry: "files": ["app/Helpers/Helper.php"]. Save the file.

Step 3

Run this command from your root directory:

composer dump-autoload

it refreshes the autoload cache.

Step 4

You can now use your class from anywhere including blade

<tr class="{{ Helper::applyClass("user") }}">

This way, you can also create global functions as well.

0

While the other solutions work pretty fine (such as inject directive), do you think it's a good practice to access a service from a blade page? I think you needed to do so because the controller or the service did not provide the necessary information to the blade. So, it would be not a bad idea to go back to controller and send what information the blade page needs to it.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.