I created some migrations using the command php artisan migrate:make and then filled it and saved it with some fields. This is a fresh installation and the first migration to run.
I ran php artisan migrate and the migration completed successfully. However, while the migrations table IS created, and it has a single row with the filename and batch 1, there is no table.
Here's my migration file code:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFuelLocationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::create('fuel_locations', function (Blueprint $table) {
$table->increments('id');
$table->string('uid');
$table->string('name');
$table->string('fuel_type');
$table->string('email');
$table->string('street');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->string('phone');
$table->string('service_hours');
$table->string('payment_methods');
$table->string('payment_method_other');
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
Schema::dropIfExists('fuel_locations');
}
}
And a few lines from my config/database.php:
'mysql' => [
'driver' => 'mysql',
'database' => 'mydb',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'charset' => env('DB_CHARSET', 'utf8'),
'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
'prefix' => env('DB_PREFIX', ''),
'timezone' => env('DB_TIMEZONE', '+00:00'),
'strict' => env('DB_STRICT_MODE', false),
],
I did try changing the host to 127.0.0.1 but that wouldn't connect. How can I fix it so that it does create the table like it's supposed to.
The problem is with the following lines:
$table->decimal('latitude', 3, 7);
$table->decimal('longitude', 3, 7);
You should be getting an exception similar to the following
[PDOException] SQLSTATE[42000]: Syntax error or access violation: 1427
For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column
'latitude').
when you do the migration.
Change to the following
$table->decimal('latitude', 10, 7);
$table->decimal('longitude', 10, 7);
and it should work.
Numeric precision refers to the maximum number of digits that are present in the number
Related
System Info:
OS: Ubuntu 19.10
Laravel Version: 7.0
PHP Version: 7.3.11-0ubuntu0.19.10.4
MySQL Version: mysql Ver 8.0.19-0ubuntu0.19.10.3 for Linux on x86_64 ((Ubuntu))
I am building a small Laravel application and am having an issue with MySQL and relationships. When I try to run my migrations, this is the error I get:
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'customers_table' (SQL: alter table `customer_contacts` add constraint `customer_contacts_customer_id_foreign` foreign key (`customer_id`) references `customers_table` (`id`))
And these are the two migration files in question.
customer table and migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->string('company_name', 50);
$table->string('phone_number', 20)->nullable();
$table->string('fax_number', 20)->nullable();
$table->string('address_line_1', 75)->nullable();
$table->string('address_line_2', 75)->nullable();
$table->string('city', 75)->nullable();
$table->string('state', 30)->nullable();
$table->string('zip', 11)->nullable();
$table->string('industry', 100)->nullable();
$table->text('notes')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('customers');
}
}
And the customer_contacts table and migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCustomerContactsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('customer_contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained('customers_table');
$table->string('name', 50);
$table->string('title', 50);
$table->string('project', 50);
$table->string('email', 50);
$table->string('mobile_phone', 20);
$table->string('work_phone', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('customer_contacts');
}
}
And this is the relevant section from my database.php file:
...
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => 'InnoDB',
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
...
I tried changing my database to SQLite to see if I get the same error and I do not, only MySQL creates this error.
Use
$table->foreignId('customer_id')->constrained('customers')
Instead of
$table->foreignId('customer_id')->constrained('customers_table');
Answer posted here: https://stackoverflow.com/a/61393131/7018549.
Use
$table->foreignId('customer_id')->constrained('customers')
Instead of
$table->foreignId('customer_id')->constrained('customers_table');
I recently changed the way my application connects to my PostgreSQL database to add the read/write principle. Since then, when I launch a migration I get the following error:
In Connection.php line 463:
[PDOException (42601)]
SQLSTATE[42601]: Syntax error: 7 ERROR: zero-length delimited identifier at or near """"
LINE 1: create table "" ("id" serial primary key not null, "migratio...
^
when I delete the database.php file, my migrations work correctly.
My .env
DB_CONNECTION=pgsql
DB_HOST=192.168.1.1
DB_PORT=5432
DB_DATABASE=database
DB_USERNAME=user
DB_PASSWORD=password
DB_USERNAME_READ=user
DB_PASSWORD_READ=password
My database.php
<?php
return [
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'read' => [
'username' => env('DB_USERNAME_READ'),
'password' => env('DB_PASSWORD_READ'),
],
'write' => [
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'sticky' => true,
'driver' => 'pgsql',
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE'),
],
],
];
and one of my migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGameUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('game_user', function (Blueprint $table) {
$table->bigInteger('game_id');
$table->bigInteger('user_id');
$table->foreign('game_id')->references('id')->on('games');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('game_user');
}
}
PHP 7.3.13
Lumen 6.3.3
PostegreSQL 9.6.2
Lumen doesn't come with a config/database.php file by default. You can either copy a default Laravel file, or create your own with your own settings.
If you've already added your own custom file, it looks like you need to specify the migrations table name.
Default entry for Laravel is 'migrations' => 'migrations', but of course you can name it whatever you like.
I got the same problem on a Laravel 7.x project.
My solution was to remove the cache of my application then to update my dependencies via composer:
php artisan cache:clear
composer update
I'm trying to seed into an orders migration file, however upon using the command: php artisan migrate:refresh --seed, the following error is being returned.
ReflectionException : Class OrdersTableSeeder does not exist
Either I'm stupid or Laravel is broken.
Seeder:
class OrdersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('orders')->insert([
'user_id' => 1,
'product_id' => 1,
'quantity' => 10,
'updated_at' => DB::raw('CURRENT_TIMESTAMP')
]);
DB::table('orders')->insert([
'user_id' => 1,
'product_id' => 2,
'quantity' => 5,
'updated_at' => DB::raw('CURRENT_TIMESTAMP')
]);
}
}
Migration:
Schema::create('orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id'); //fk
$table->integer('product_id'); //fk
$table->integer('quantity');
$table->timestamps();
});
Class doesn't exists error seems that Laravel couldn't find the class named OrdersTableSeeder.
I hope that using the below command helps.
composer dump-autoload
Explanation:
Why do I have to run "composer dump-autoload" command to make migrations work in laravel?
I am trying to migrate my postgresql table, but when launch the command php artisan migrate it return the follow error:
SQLSTATE[08P01]: <>: 7 ERROR: bind message supplies 1 parameters, but prepared statement "pdo_stmt_00000003" requires 2 (SQL: select * from information_schema.tables
where table_schema = migrations and table_name = ?)
One of my migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateSchedulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedules', function(Blueprint $table)
{
$table->increments('id');
$table->string('schedule_name')->unique();
$table->integer('parent_id')->unsigned()->nullable();
$table->integer('launch_sequence_id')->unsigned();
$table->string('day_of_week', 10)->nullable();
$table->string('command_type', 50);
$table->integer('hours')->unsigned()->nullable();
$table->integer('minutes')->unsigned()->nullable();
$table->integer('dd')->unsigned()->nullable();
$table->integer('mm')->unsigned()->nullable();
$table->integer('yyyy')->unsigned()->nullable();
$table->boolean('enabled')->default(1);
$table->boolean('ascending')->default(0);
$table->dateTime('last_execution')->nullable();
$table->dateTime('last_success')->nullable();
$table->integer('retry')->default(0);
$table->timestamps();
$table->softDeletes();
});
DB::statement('ALTER TABLE schedules ADD CONSTRAINT day_of_week_check CHECK ((day_of_week)::text = ANY (ARRAY[(\'all\'::character varying)::text, (\'monday\'::character varying)::text, (\'tuesday\'::character varying)::text, (\'wednesday\'::character varying)::text, (\'thursday\'::character varying)::text, (\'friday\'::character varying)::text, (\'saturday\'::character varying)::text, (\'sunday\'::character varying)::text]))');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('schedules');
}
}
And my database configuration:
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => env('DB_SCHEMA', 'public'),
//'sslmode' => 'prefer',
]
],
My .env
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=livion
DB_USERNAME=livion
DB_PASSWORD=secret
DB_SCHEMA=public
I tried to track it down and seems that it doesn't use the correct grammar for the function repositoryExists, it uses the default grammar witch doesn't send the schema parameter.
The other query executed via model or repository works fine, I get this error only for the migration command.
Any suggestion to solve this problem?
I figure out the problem.
I migrated the project from laravel 5.3 to 5.5 and the old project used the module Aejnsn\Postgresify.
It causes my problem on migration.
Remove it and all works again.
I'm trying to make following tutorial: https://medium.com/on-coding/e8d93c9ce0e2
When it comes to run:
php artisan migrate
I get following error:
[Exception]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel.user' doesn't
exist (SQL: alter table `user` add `id` int unsigned not null auto_increment prim
ary key, add `username` varchar(255) null, add `password` varchar(255) null, add
`email` varchar(255) null, add `created_at` datetime null, add `updated_at` datet
ime null) (Bindings: array (
))
Database connection is working, the migrations table was created successfully. Database name was changed as you can see in the error message.
Whats quite strange to me, is that it tries to alter the table - which doesn't exists - and not to create it.
Here are my other files, like UserModel, Seeder, Migtation and DB Config.
CreateUserTable:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('user', function(Blueprint $table)
{
$table->increments("id");
$table
->string("username")
->nullable()
->default(null);
$table
->string("password")
->nullable()
->default(null);
$table
->string("email")
->nullable()
->default(null);
$table
->dateTime("created_at")
->nullable()
->default(null);
$table
->dateTime("updated_at")
->nullable()
->default(null);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('user', function(Blueprint $table)
{
Schema::dropIfExists("user");
});
}
}
UserModel:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
UserSeeder:
class UserSeeder extends DatabaseSeeder
{
public function run()
{
$users = [
[
"username" => "ihkawiss",
"password" => Hash::make("123456"),
"email" => "ihkawiss#domain.com"
]
];
foreach ($users as $user)
{
User::create($user);
}
}
}
DatabaseSeeder:
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call('UserSeeder');
}
}
Database Config:
return array(
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => 'mysql',
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/production.sqlite',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
),
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => array(
'cluster' => true,
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
),
);
Hope somebody can give me a hint here.
Best regards ihkawiss
In your CreateUserTable migration file, instead of Schema::table you have to use Schema::create.
The Schema::table is used to alter an existing table and the Schema::create is used to create new table.
Check the documentation:
http://laravel.com/docs/schema#creating-and-dropping-tables
http://laravel.com/docs/schema#adding-columns
So your user migration will be:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user', function(Blueprint $table) {
{
$table->increments("id",true);
$table->string("username")->nullable()->default(null);
$table->string("password")->nullable()->default(null);
$table->string("email")->nullable()->default(null);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists("user");
}
}
The underlying cause of this may be if the syntax used for creating the migration php artisan migrate ... is not quite correct. In this case the --create will not get picked up properly and you will see the Schema::table instead of the expected Schema::create. When a migration file is generated like this you might also be missing some of the other markers for a create migration such as the $table->increments('id'); and $table->timestamps();
For example, these two commands will not create a create table migration file as you might expect:
php artisan migrate:make create_tasks_table --table="tasks" --create
php artisan migrate:make create_tasks2_table --table=tasks2 --create
However, the command will not fail with an error. Instead laravel will create a migration file using Schema::table
I always just use the full syntax when creating a new migration file like this:
php artisan migrate:make create_tasks_table --table=tasks --create=tasks
to avoid any issues like this.
Sometimes it is caused by custom artisan commands. Some of these commands might initiate few classes. And because we did a rollback, the table cannot be found. Check you custom artisan commands. You can comment out the lines which are causing the trigger. Run the php artisan migrate command and then uncomment. This is what I had to do.