Custom class in laravel

370 Views Asked by At

I've created a custom class inside the app/Helpers folder.

I want to access it in views like Helper::someMethod(). I tried to bind it in IoC. But couldn't get it working. The following is my Helper class:

class ApplicationHelpers {
    public function me() {
        return "this is me!";
    }
}

This is how I bind it in the AppServiceProvider class in register method.

$this->app->make('App\Helpers\ApplicationHelpers');

And this is how I want to access in view.

<div class="title m-b-md">
   {{ ApplicationHelpers::me() }}
</div>

How can I achieve this?

3

There are 3 best solutions below

0
On

If you do not register the class anywhere, you have to include the namespace. So it would look like this:

<div class="title m-b-md">
   {{ \App\Helpers\ApplicationHelpers::me() }}
</div>

Or you can create an alias in your config/app.php and then call the class directly.

2
On

Inside config/app.php aliases array add this line

'Helper' => App\Helpers\Helper::class, //your class path

then use composer dump-autoload

Then you can use helper function in view like this

{{Helper::userInfo()}} or {{Helper->userInfo()}}

Helper is alias name and function. use :: or -> based on function definition.

0
On

if you want to add simple functions helpers you can also edit your composer.json file and add the path to your helper file

"autoload": {
    "files": [
        "app/Http/ApplicationHelpers.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

where you can declare simple function such as me()

function me() {
    return "this is me!";
}

then call composer dump-autoload so you can simply call

<div class="title m-b-md">
   {{ me() }}
</div>