0

I've created a helper file in App folder named as Helper.php.

app/Helper.php

<?php

namespace App;

use Illuminate\Support\Facades\DB;

class Helper {

    public function get_username($user_id) 
    {
        $user = DB::table('users')->where('userid', $user_id)->first();

        return (isset($user->username) ? $user->username : '');
    }
}

app/Providers/HelperServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
    }

    public function register()
    {
        require_once app_path() . 'Helper.php';
    }
}

config/app.php

Inside the provider's array...

App\Providers\HelperServiceProvider::class,

Inside aliases array...

'Helper' => App\Helper::class,

Everything was working fine but now I have the following error.

ErrorException thrown with message "Non-static method Helper::get_username($user->id) should not be called statically

But when I add static keyword to function its works fine. What's the difference between static and non-static methods?

1 Answer 1

0

Aliases give you the possibility to access a facade in a blade template without adding it in the template (vie use statement). When calling a method via a facade, you call this method statically and the facade will call the object of the class containing this method.

In Laravel, it is usually more convenient to create a file containing helpers like Laravel does and to autoload that file via composer.

Please check here for more details

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.