Laravel: Migration & Seeding Problems - laravel

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

Related

Laravel 8 General error: 1215 Cannot add foreign key constraint

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');

Foreign key constraint is incorrectly formed in laravel 7

I am building a hotel management application using laravel. I am trying to create the tables 'reservations' in laravel but when I run the 'migrate:fresh' command, I get the following: error "Foreign key constraint is incorrectly formed". Can anyone tell what do you mean by this error?
View Error
public function up()
{
Schema::create('room_types', function (Blueprint $table) {
$table->id();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('short_code')->unique();
$table->longText('description')->nullable();
$table->integer('base_capacity')->default(0);
$table->integer('higher_capacity')->default(0);
$table->boolean('extra_bed')->default(0);
$table->integer('kids_capacity')->default(0);
$table->float('base_price',8,2)->default(0);
$table->float('additional_person_price',8,2)->default(0);
$table->float('extra_bed_price',8,2)->default(0);
$table->boolean('status')->default(1);
$table->softDeletes();
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('usertype')->default('user');
$table->string('last_name')->nullable();
$table->string('phone')->nullable();
$table->date('dob')->nullable();
$table->longText('address')->nullable();
$table->enum('sex',['M','F','O'])->default('M');
$table->string('picture')->nullable();
$table->string('id_type')->nullable();
$table->string('id_number')->nullable();
$table->string('id_card_image_front')->nullable();
$table->string('id_card_image_back')->nullable();
$table->string('company_name')->nullable();
$table->string('gst_no')->nullable();
$table->text('remarks')->nullable();
$table->boolean('vip')->default(0);
$table->boolean('status')->default(1);
$table->rememberToken();
$table->timestamps();
});
}
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
Error message
SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `reservations` add constraint `reservations_reservations_user_id_foreign` foreign key (`reservations_user_id`) references `users` (`id`) on delete cascade)
at C:\xampp\htdocs\hotelplex\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:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `hotelplex`.`reservations` (errno: 150 "Foreign key constraint is incorrectly formed")")
2 C:\xampp\htdocs\hotelplex\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Laravel6
Laravel6 does not have any method id() to create id in a table. Laravel7 does.. I tried creating id using $table->id() using Laravel6 and got the below error.
It seems you posted wrong error or you have already created id manually in your tables.
You can use bigIncrements,bigInteger, increments,integer etc.
You can find all available methods here
Laravel7
As per Laravel7 $table->id() is alias of Alias of $table->bigIncrements('id') i.e. unsigned big integer.
To create Foreign key the data type for the child column must match the parent column exactly.
Since users.id and room_types.id is a bigIncrements then reservations.user_id and reservations.room_type_id also needs to be an unsignedbigInteger, not a unsignedInteger.
So to make it work
change
$table->unsignedInteger('user_id');
$table->unsignedInteger('room_type_id');
to
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
Like this:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}
https://laravel.com/docs/7.x/migrations#creating-columns
The problem seems to be of data type mismatching for user_id and room_type_id
$table->id(); alias of Alias of $table->bigIncrements('id');
https://laravel.com/docs/master/migrations#columns
So, you need foreign user_id and room_type_id column on reservations like:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
...
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
...
})
}
on laravel 8, you can use this
$table->id();
....
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
...
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('restrict');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('restrict');
The ->onDelete('cascade'); should be on the relationships creation part.
Change the to:
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
// Structure
$table->id();
$table->integer('uid')->unique();
$table->timestamp('date');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('room_type_id');
$table->integer('adults')->default(1);
$table->integer('kids')->default(0);
$table->date('check_in');
$table->date('check_out');
$table->integer('number_of_room')->default(1);
$table->enum('status',['PENDING','CANCEL','SUCCESS'])->default('PENDING');
$table->timestamps();
// Relationships
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('room_type_id')->references('id')->on('room_types')->onDelete('cascade');
});
}

Error is raised on seeding with index defined

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 !

errno: 150 "Foreign key constraint is incorrectly formed" in Laravel

Schema::create('position', function (Blueprint $table) {
$table->increments('post_id');
$table->String('post_name');
$table->timestamps();
});
Schema::create('candidate', function (Blueprint $table) {
$table->increments('id');
$table->String('name');
$table->String('branch');
$table->unsignedInteger('post_id');
// $table->foreign('post_id_no')->references('post_id')->on('position')->onDelete('cascade');
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
$table->integer('count')->default(0);
$table->timestamps();
});
I have two tables, position and candidate. When I migrate I get error for foreign key. can anyone say whats error in code?
This is error I get when I migrate:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table voting.#sql-16b7_2b (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table candidate add constraint candidate_post_id_foreign foreign key (post_id) references position (post_id) on delete cascade)
catch (Exception $e) {
throw new QueryException(
$query, $this->prepareBindings($bindings), $e
);
}
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `voting`.`#sql-16b7_2b` (errno: 150 "Foreign key constraint is incorrectly formed")")
Likely a mismatch on the foreign key column and the referencing column possibly not being the same type or length. Instead of
$table->unsignedInteger('post_id');
in your candidate table, try:
$table->integer('post_id')->unsigned()->index();
Also, it is sometimes helpful and more clear (perhaps to mysql) to keep the original (position) id as just 'id'. You can call it post_id in the candidate table and reference 'id' on position. A little easier to understand.
You need to specify your default-engine as
$table->engine = 'InnoDB';
And make sure you have created the position table which the table candidate is referencing to. Please add your voting table schema in the post too.
You can try this.
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('post_id')->on('position')->onDelete('cascade');
This worked for me. Thank you.
public function up() { Schema::create('companies', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('address'); $table->string('tel1'); $table->string('tel2'); $table->integer('owner'); $table->unsignedBigInteger('access_id'); $table->string('depot_number')->default(2); $table->timestamps(); $table->foreign('access_id')->references('id')->on('accesses') ->onDelete('cascade'); }); }
public function up() { Schema::create('accesses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('type'); $table->string('description'); $table->timestamps(); }); }
In your database/migrations folder, sort by name. Then make sure create_accesses_table is before create_companies_table:
enter image description here

Cannot create foreign key

I want to create a foreign key that is string from table "stocks" to "rfids".
The two tables are shown below.
stocks table:
Schema::create('stocks', function (Blueprint $table) {
$table->increments('tag_no');
$table->string('stock_type');
$table->string('rfid');
$table->foreign('rfid')->references('RFID_UID')->on('rfids');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
rfids table:
Schema::create('rfids', function (Blueprint $table) {
$table->increments('id');
$table->string('RFID_UID');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
When i use php artisan migrate it shows error.
SQLSTATE[HY000]: General error: 1005 Can't create table hardware.#sql-81c_c8 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table stocks
add constraint stocks_rfid_foreign foreign key (rfid) references rfids (RFID_UID))
Someone help me pls!
The migration order is crucial. You have to create the referenced table (rfids) first.
You can order the migrations by changing the date/time in the filename.
I changed the tables this way:
Schema::create('rfids', function (Blueprint $table) {
$table->increments('id');
$table->string('RFID_UID');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('stocks', function (Blueprint $table) {
$table->increments('tag_no');
$table->string('stock_type');
$table->string('rfid');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Instead of using foreign key i did the following while storing
public function store(Request $request)
{
//
if(Auth::check()){
if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) {
return back()->withInput()->with('errors', 'Tag number already used!');
}
$rfid_tag = Rfid::where('id',"=",$request->input('tag_no'))->first();
$stock = Stock::create([
'tag_no' => $request->input('tag_no'),
'stock_type' => $request->input('stock_type'),
'species' => $request->input('species'),
'rfid'=>$rfid_tag->RFID_UID,
'user_id' => Auth::user()->id
]);
if($stock){
return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
->with('success' , 'Stock created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new Stock');
}
It works fine for me. But idk if its the right solution.

Resources