FareedR's avatar

How can I use this as a helper?

I got an error "Call to undefined function App\loginIdExists()" anyone can show the right method ?

public static function generateLoginId() {
        $number = mt_rand(1000000000, 9999999999); // better than rand()
    
        // call the same function if the barcode exists already
        if (loginIdExists($number)) {
            return generateLoginId();
        }
        // otherwise, it's valid and can be used
        return $number;
    }
    
    public static function loginIdExists($number) {
        // query the database and return a boolean
        // for instance, it might look like this in Laravel
        $concated_number = 'COD'.$number;
        return User::where('login_id',$concated_number)->exists();
    }
0 likes
10 replies
jlrdw's avatar

If that's in a separate class make sure to use the use statement in the controller.

FareedR's avatar

@jlrdw current script as below . but i got an error like above .

use App\Helpers;

$test = Helpers::generateLoginId();
dd($test);
jlrdw's avatar

Is Helpers also the name of the class. If so that should work. You do have Helpers.php and the app folder correct.

Edit: did you remember to give that class a namespace.

FareedR's avatar

@jlrdw i tried .

// helpers.php
namespace App;

use App\User;

class Helpers {
   public static function generateLoginId() {
        $number = mt_rand(1000000000, 9999999999); // better than rand()
        if (loginIdExists($number)) {
            return generateLoginId();
        }

        return $number;
    }
    
    public static function loginIdExists($number) {
        $concated_number = 'MLI'.$number;
        return User::where('login_id',$concated_number)->exists();
    }
}

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

// controller 
use App\Helpers;

$test = Helpers::generateLoginId();
dd($test);
jlrdw's avatar

Make a custom helper class. In its own file.

jlrdw's avatar

I also have custom classes. I guess try to dumpautoload.

But when I put something under app I've never had to dump Autoload.

Can you show the whole class.

MichalOravec's avatar

@fareedr Laravel follows psr-4 so if your namespace is App then your file has to be in app directory as

app/Helpers.php

jlrdw's avatar

And to use

Use App\Helpers;

What folder did you have it in?

I mentioned under app.

Please or to participate in this conversation.