0

I am trying to create public funtions using for loop here is an example about what I want to do:

class databaseController extends Controller
{
   for ($i=0; $i < 5; $i++) {
    # code...

        public function create()
        {

            // dd('hoi_tb1_create'); 
            if (Auth::guard('admin')->user()->level == 2) {
                Schema::connection('mysql')->create('tb' . $i, function (
                    $table
                ) {
                    $table->increments('id');
                });
            }

            // get all products
        }
    }
}

have you any idea how to do that?

Thanks in advance Somur

Simon R
  • 3,732
  • 4
  • 31
  • 39
  • 1
    I'm not sure if you are able to do that. But what is it that you're trying to achieve? There probably is a better solution for it. – Tom Oct 13 '19 at 09:41
  • Hope [this](https://stackoverflow.com/questions/8549496/how-can-i-create-a-function-dynamically) can help you – boolfalse Oct 13 '19 at 11:24

1 Answers1

0

You could use a second function to get this to work

class LoopController extends Controller
{
    public function create($i)
    {
        if (Auth::guard('admin')->user()->level == 2) {
            Schema::connection('mysql')->create('tb' . $i, function ($table) {
                $table->increments('id');
            });
        }
    }

    public function createMany()
    {
        for($i = 0; $i < 5; $i++) {
            $this->create($i);
        }
    }
}

The create function takes in a parameter of $i, but is not called directly from the route, instead you'd call createMany() which has a for loop in it. This will call create 5 times, each time passing its iterater value in e.g. 0, 1, 2, 3, 4.

Alternatively, if you're wanting these functions to be invoked independently, you could use PHP's magic method to dynamically call the create function. For example you could grab all of the numbers after create and then call create(numbers);

class LoopController extends Controller
{
    public function create($i)
    {
        if (Auth::guard('admin')->user()->level == 2) {
            Schema::connection('mysql')->create('tb' . $i, function ($table) {
                $table->increments('id');
            });
        }
    }

    public function __call($method, $parameters)
    {
        if (preg_match('/create([\d]+)/', $method, $matches)) {
            return $this->create($matches[1]);
        }

        throw new \BadMethodCallException("Method " . get_class($this) . "::$method does not exist");
    }
}

So now if you call LoopController->create48(); It will then call ->create(48);

Simon R
  • 3,732
  • 4
  • 31
  • 39