8

Apologies if this have been asked, but I don't seem to find the right answer.

I need to create a table in the DB from a Controller.

I was naive enough to believe the below would work:

    Schema::connection('mysql')->create('mytable_'.$id, function($table)
    {
        $table->increments('id');
        $table->timestamps();
    });

Where $id is a dynamic value passed into the controller's function.

I've placed the below on the top:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

No luck - How can a DB table be created from the controller then? Any ideas?

Error: enter image description here

Solution As Ben Swinburne has said in the first comment, the use Schema was missing!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Inigo EC
  • 2,178
  • 3
  • 22
  • 31

2 Answers2

5

You're using the Schema facade.

Make sure you have use Schema; at the top of your file too.

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
1

I think best approach will be creating a migration and running php artisan migrate command from your controller:

Artisan::call('migrate');

If you do not know how to create migrations from code using stubs, you can learn that from some well-written package. I've learned how to do that from this package.

Hope this will help

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Some times you just need to create a table inside a controller. eg: I am importing some contacts, I wish to load that to a temp table, then delete it later. I obviously cant use a general purpose common table, since on a multi-user environment, more than one person may be using the "general purpose table" – Azmeer Feb 24 '21 at 17:25