Inigo EC
Inigo EC

Reputation: 2328

Laravel 5.2 - Create Database table from a Controller

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!

Upvotes: 8

Views: 9908

Answers (2)

Ben Swinburne
Ben Swinburne

Reputation: 26467

You're using the Schema facade.

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

Upvotes: 5

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

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

Upvotes: 1

Related Questions