mpouya's avatar

How to call a class and its static method dynamically in laravel?

Hi, I wrote a command and pass the name of the class like this:

use App\Models\Brand;
...

class GeneralCommand extends Command
{
	    public function sanitizingData($classNames){

        foreach($classNames as $clasName){
            
            $clasName::chunk(100, function ($brands) {
                foreach ($brands as $brand) {

                    dd($brand);
                
                    //Other stuff
                }
            });

        }

    }
}

then when I call this command like this:

php artisan general:cmd sanitizingData Brand,Property;

It generates this error:

  Class 'Brand' not found

  at app/Console/Commands/GeneralCommand.php:184
    180|     public function sanitizingData($classNames){
    181| 
    182|         foreach($classNames as $clasName){
    183|             
  > 184|             $clasName::chunk(100, function ($brands) {
    185|                 foreach ($brands as $brand) {
    186| 
    187|                     dd($brand);
    188|                 

  • A class import is missing: You have a missing class import. Try importing this class: `App\Models\Brand`.

I've already imported Brand class and it works if I call it in the normal way, but it's not working when I call it dynamically.

0 likes
4 replies
SilenceBringer's avatar
Level 55

@mpouya try to prepend it with namespace

				foreach ($brands as $brand) {
					$brand = '\App\Models\' . $brand;
                    dd($brand::staticMethod());
                
                    //Other stuff
                }
1 like

Please or to participate in this conversation.