In laravel 5.8 app I created migration file with 1 field and 1 index added
class SubscriptionsTableAddIsFreeField extends Migration
{
public function up()
{
Schema::table('subscriptions', function (Blueprint $table) {
$table->boolean('is_free')->default(false)->after('source_service_subscription_id');
$table->index([ 'user_id', 'is_free' ], 'subscriptions_user_id_is_free_index');
});
}
public function down()
{
Schema::table('subscriptions', function (Blueprint $table) {
$table->dropForeign('subscriptions_user_id_is_free_index');
$table->dropColumn('is_free');
});
}
But running command
php artisan migrate:refresh --seed
I got error :
: SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists (SQL: alter table `vt2_subscriptions` drop foreign key `subscriptions_user_id_is_free_index`)
at /mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
/mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119
2 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'subscriptions_user_id_is_free_index'; check that column/key exists")
/mnt/_work_sdb8/wwwroot/lar/votes/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117
Please use the argument -v to see more details.
What is wrong in defintion of my migration?
I know that laravel migration has methods
if (Schema::hasTable('users')) {
//
}
if (Schema::hasColumn('users', 'email')) {
//
}
But can I check indexes?
With this How can indexes be checked if they exist in a Laravel migration? link I found a proper checking:
Schema::table('subscriptions', function (Blueprint $table) {
$sm = Schema::getConnection()->getDoctrineSchemaManager();
$indexesFound = $sm->listTableIndexes('subscriptions');
if(array_key_exists("subscriptions_user_id_is_free_index", $indexesFound)) {
$table->dropUnique("subscriptions_user_id_is_free_index");
}
$table->dropColumn('is_free');
});
It works for me !
Related
I get this error when i want to create teble from artisan tool.
Migrating: 2022_06_06_114027_create_subjekat_adrese_table
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `subjekat_adrese` add constraint `subjekat_adrese_subjekti_id_foreign` foreign key (`subjekti_id`) references `subjekti` (`id`) on delete cascade)
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712
708▕ // If an exception occurs when attempting to run a query, we'll format the error
709▕ // message to include the bindings with SQL, which will make this exception a
710▕ // lot more helpful to the developer instead of just the database's errors.
711▕ catch (Exception $e) {
➜ 712▕ throw new QueryException(
713▕ $query, $this->prepareBindings($bindings), $e
714▕ );
715▕ }
716▕ }
+9 vendor frames
10 database/migrations/2022_06_06_114027_create_subjekat_adrese_table.php:37
Illuminate\Support\Facades\Facade::__callStatic("create")
+22 vendor frames
33 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
What i try:
public function up()
{
Schema::create('subjekat_adrese', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('naziv');
$table->string('adresa');
$table->boolean('primarna')->unique();
$table->bigInteger('subjekti_id')->index();
$table->bigInteger('drzave_id')->index();
$table->bigInteger('gradovi_id')->index();
$table->bigInteger('poste_id')->index();
$table->timestamps();
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');
$table->foreign('drzave_id')->references('id')->on('drzave')->onDelete('SET NULL');
$table->foreign('gradovi_id')->references('id')->on('gradovi')->onDelete('SET NULL');
$table->foreign('poste_id')->references('id')->on('poste')->onDelete('SET NULL');
});
Try 2
public function up()
{
Schema::create('subjekat_adrese', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('naziv');
$table->string('adresa');
$table->boolean('primarna')->unique();
$table->bigInteger('subjekti_id')->index();
$table->bigInteger('drzave_id')->index();
$table->bigInteger('gradovi_id')->index();
$table->bigInteger('poste_id')->index();
$table->timestamps();
});
Schema::table('subjekat_adrese', function($table) {
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');
$table->foreign('drzave_id')->references('id')->on('drzave')->onDelete('SET NULL');
$table->foreign('gradovi_id')->references('id')->on('gradovi')->onDelete('SET NULL');
$table->foreign('poste_id')->references('id')->on('poste')->onDelete('SET NULL');
});
}
I dont know what to try next but nothing not wotk.
$table->foreignId('user_id')->constrained()->onDelete('cascade');
you tried it in this way to see ??
I mean this way instead of
$table->foreign('subjekti_id')->references('id')->on('subjekti')->onDelete('cascade');
I am trying to seed a database and am getting an error when I run php artisan migrate:fresh:
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `news` add constraint `news_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)
at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
2 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Here are the migration files:
Schema::create('news', function (Blueprint $table) {
$table->bigIncrements('id');
...
$table->unsignedBigInteger('author_id');
$table->foreign('author_id')
->references('id')
->on('authors')
->onDelete('cascade');
});
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
And here are the factory files:
$factory->define(Author::class, function (Faker $faker) {
return [
'name' => $faker->name
];
});
return [
...
'author_id' => $faker->numberBetween($min = 1, $max = 50),
];
And finally, here are the seed files:
// DatabaseSeeder
{
$this->call(AuthorsTableSeeder::class);
$this->call(NewsTableSeeder::class);
}
// NewsSeeder and AuthorSeeder
factory(App\News::class, 150)->create();
factory(App\Authors::class, 50)->create();
Any idea why I am getting this error and what I can do to fix it?
Thanks.
simply because the migration file for news runs before authors
just try to change the timestamp for these two files to make authors migration run before news migration
PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 Yo
u have an error in your SQL syntax; check the manual that corresponds to your Ma
riaDB server version for the right syntax to use near ') on delete CASCADE' at l
ine 1")
C:\xampp\htdocs\projek\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
PDO::prepare("alter table pengerjaan add constraint pengerjaan_id_kateg
ori_foreign foreign key (id_kategori) references kategori () on delete CASC
ADE")
C:\xampp\htdocs\projek\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
public function up(){
Schema::create('pengerjaan', function (Blueprint $table) {
$table->increments('id');
$table->unsignedinteger('id_kategori');
$table->unsignedinteger('id_pelanggan');
$table->enum('status', array('proses', 'pending', 'hasil'));
$table->datetime('apply_date');
$table->timestamps();
$table->foreign('id_kategori')->refrences('id')->on('kategori')->onDelete('CASCADE');
$table->foreign('id_pelanggan')->refrences('id')->on('pelanggan')->onDelete('CASCADE');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('pengerjaan');
}
You have a spelling error, it is not refrences but it is references so change this two lines:
$table->foreign('id_kategori')->refrences('id')->on('kategori')->onDelete('CASCADE');
$table->foreign('id_pelanggan')->refrences('id')->on('pelanggan')->onDelete('CASCADE');
with this:
$table->foreign('id_kategori')->references('id')->on('kategori')->onDelete('cascade');
$table->foreign('id_pelanggan')->references('id')->on('pelanggan')->onDelete('cascade');
I'm about to refresh my migration. But php artisan migrate:refresh command is not working.
It shows the following error:
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error
or access violation: 1091 Can't DROP 'classes_userid_foreign'; check
that column/key exists (SQL: alter table classes drop foreign key
classes_userid_foreign)
[PDOException] SQLSTATE[42000]: Syntax error or access violation:
1091 Can't DROP 'classes_userid_foreign'; check that column/key
exists
I even used the dropForeign but its not working for me.
I'm showing my migration file
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->integer('userId')->unsigned();
$table->string('title');
$table->string('name');
$table->string('code')->unique();
$table->integer('capacity')->unsigned();
$table->integer('tagId')->unsigned();
$table->foreign('userId')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('classes', function (Blueprint $table) {
$table->dropForeign(['userId']);
});
Schema::drop('classes');
}
How to fix this problem ?
Most times when you run migrations in laravel (whether up or down), and an error occurs along the line, the transaction may have completed partially without registering it in the migrations table.
If this is the case, or you will like to drop tables whether or not there really exists a foreign key, then you should consider disabling foreign key checks like so:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::drop('classes');
Schema::enableForeignKeyConstraints();
}
I am trying to add unique to slug in products table and I have the following migration. However when I run php artisan migrate I get an error.
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUniqueToProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->unique('slug');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropUnique('products_slug_unique');
});
}
}
Error
➜ php artisan migrate
[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry '' for key
'products_slug_unique' (SQL: alter table products add unique
products_slug_unique(slug))
[Doctrine\DBAL\Driver\PDOException] SQLSTATE[23000]: Integrity
constraint violation: 1062 Duplicate entry '' for key
'products_slug_unique'
[PDOException] SQLSTATE[23000]: Integrity constraint violation:
1062 Duplicate entry '' for key 'products_slug_unique'
What am I doing wrong here?
You can create normal field of 'slug' and create data type of slug is 'string' and you can use validator to create unique slugs, in this case you can give custom response also.
$validator = Validator::make($request->all(), [
'slug' => 'required|string|unique:products'
]);
if ($validator->fails()){
//custom response
}
Set the default for unique column to NULL before putting constraint. Since the values in slug is net to empty but not null MySql is expecting '' to be unique itself, thus preventing unique constraint on column.
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::statement('UPDATE products SET slug = NULL;');
Schema::table('products', function (Blueprint $table) {
$table->unique('slug');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropUnique('products_slug_unique');
});
DB::statement("UPDATE products SET slug = '';");
}
As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:
use Illuminate\Database\Schema\Builder;
public function boot()
{
Builder::defaultStringLength(191);
}