Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 764
Inigo EC Avatar asked Apr 01 '16 16:04

Inigo EC


People also ask

Can Laravel create database?

Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app/config/database. php . In this file you may define all of your database connections, as well as specify which connection should be used by default.

How can we get data from database in controller in Laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.

Which method is used to create a table in Laravel?

Step 1: To create a table we need to use the create method which is available on the Schema facade. The schema has got many column methods of which you can use the desired format to define the column of the table in a plan. The hashtable and hashcolumn methods help you to check for existing tables.


1 Answers

You're using the Schema facade.

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

like image 156
Ben Swinburne Avatar answered Sep 17 '22 20:09

Ben Swinburne