How do I implement a "foreignId( )" migration in laravel 9? - laravel-9

public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->uuid()->unique();
$table->string('title')->nullable();
$table->longText('body')->nullable();
$table->string('image')->nullable();
$table->foreignId('user_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
$table->foreignId('category_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
$table->timestamps();
});
}
SQLSTATE[HY000]: General error: 1005 Can't create table blog_test_db.posts (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table posts add constraint posts_category_foreign foreign key (category) references categories (id) on delete cascade on update cascade)

Related

Error SQLSTATE[HY000]: General error: 1005 Can't create table in ACL Permission and Role Laravel 8

do not be tired. My program has a problem, please check the following code. thank you
The codes give this error:
SQLSTATE[HY000]: General error: 1005 Can't create table term_laravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)
Uploaded photo error link: enter image description here
Important Note: migration failed to create the table. So with the command migrate: reset, migrate: fresh does not delete. The table must be manually referenced by phpmyadmin and the table
I remove role_user, permisstions, roles.
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('title')->nullable();
$table->timestamps();
});
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('title')->nullable();
$table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('user_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
$table->primary(['role_id','user_id']);
});
Schema::create('permission_role', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('permission_id');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('permission_id')
->references('id')
->on('permissions')
->onDelete('cascade')
->onUpdate('cascade');
$table->primary(['permission_id','role_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('permission_and_roles');
}
}

The used table type doesn't support FULLTEXT indexes (SQL: ALTER TABLE product_translations ADD FULLTEXT(name))

You can help me with this error i dont know to change to MyISAM engine, I see other post with this error.
SQLSTATE[HY000]: General error: 1214 The used table type doesn't support FULLTEXT indexes (SQL: ALTER TABLE product_translations ADD FULLTEXT(name))
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductTranslationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product_translations', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->string('locale');
$table->string('name');
$table->longText('description');
$table->text('short_description')->nullable();
$table->unique(['product_id', 'locale']);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
DB::statement('ALTER TABLE product_translations ADD FULLTEXT(name)');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product_translations');
}
}

SQLSTATE[23000]: Integrity constraint violation 1452 Cannot add or update a child row: a foreign key constraint fails

I have this migration file
class AddRolesFieldsToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->foreignId('role_id')->constrained();
$table->string('student_address')->nullable();
$table->string('student_licence_number')->nullable();
$table->string('teacher_qualifications')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
And a User model has all fillables like seen below
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'role_id',
'student_address',
'student_licence_number',
'teacher_qualifications',
];
But I get the SQLSTATE[23000]: Integrity constraint violation 1452 Cannot add or update a child row: a foreign key constraint fails when I try to register a new user, how should I fix this?
To solve this, manually insert the roles value into the database.
So for the first row:
id=2 | name=Teacher | created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00
Second row:
id=3 | name=Student| created_at =0000-00-00 00:00:00|updated_at 0000-00-00 00:00:00

Creating a joined table with laravel

I am using Laravel 6. I want to create a joined table named meeting_user that should connect the tables meetings and users. That's considering that a user could participate to many meetings and a meeting could have many users.
users:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('username')->unique();
$table->string('password');
$table->enum('permission', array(0, 1, 2));
$table->enum('is_active', array(0, 1))->default(1);
$table->rememberToken();
$table->timestamps();
});
meetings:
Schema::create('meetings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('description');
$table->string('id_room');
$table->date('date');
$table->time('start_hour');
$table->time('end_hour');
$table->enum('is_active', array(0, 1))->default(1);;
$table->timestamps();
$table->foreign('id_room')->references('id')->on('rooms');
});
I would like to create this table with a migration and furthermore I would like that when a user creates a meeting with many users and so inserts a new row to the "meetings" table, even the new "meeting_user" table be dynamically filled in adding new rows. Is there a way to do that with Laravel?
you have to create a third table
called for example "user_meetings"
and it's migration will be
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('meeting_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')-
>onDelete('cascade');
$table->foreign('meeting_id')->references('id')->on('meetings')-
>onDelete('cascade');
and then put the relation in "user" model
public function meetings()
{
return $this->belongsToMany(Meeting::class, 'user_meetings', 'user_id', 'meeting_id');
}
and the relation in "meeting" model
public function users()
{
return $this->belongsToMany(User::class, 'user_meetings', 'meeting_id', 'user_id');
}
and the code of "adding" meetings in the controller will be
$user->meetings()->attach($request->meetings);
return redirect()->back()->with('success', 'successfull');
and "edit"
$checker->meetings()->sync($request->meetings);
return redirect()->back()->with('success', 'successfull');
and "delete"
$checker->meetings()->detach();
i hope these steps will help you

SQLSTATE[HY000]: General error: 1 unknown column "user_id" in foreign key definition

I have this error when i run :
php artisan migrate:fresh
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1 unknown column "user_id" in foreign key definition (SQL:
create table "users" ("id" integer not null primary key autoincrement,
"name" varchar not null, "email" varchar not null, "username" varchar
not null, "email_verified_at" datetime null, "password" varchar not
null, "remember_token" varchar null, "created_at" datetime null,
"updated_at" datetime null, foreign key("user_id") references
"users"("id") on delete cascade))
I'm following a video tutorial on youtube, and the code of the tutorial is this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
If I copy and paste this code I have the error. So i searched on stackoverflow and I've found this solution:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
Schema::table('profiles', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('profiles');
}
This is my users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('users');
}
But today, when i run php artisan migrate:fresh I had this error again.
How can I solve?
Thanks
As others have mentioned, user_id isn't a column in your users table, but you are trying to create an index on it. This line:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
belongs in the profiles table creation schema and not in the users table creation schema.
The full code:
// create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
// create_profiles_table.php <-- migrate AFTER users table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
The error is clearly mention here:
foreign key("user_id") references "users"("id") on delete cascade)
and you don't have a column with name user_id
The syntax is:
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns) <-- this must be a column in the table
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
but in your case user_id column is not available in the query. So either add the that column or remove this constraint code and try again.
The reason for this problem is that the profile table was created before the user table.
I have a trick for problem solve.
You should rename migration files in the migration directory.
for example let my file names be like this
2019_06_10_000001_create_users_table.php
2019_06_10_000002_create_profiles_table.php
first user table is created when you run "artisan migrate or migrate:fresh"
why? because first created migration file is user file.You should look carefully
2019_06_10_000001 -> users table name
2019_06_10_000002 -> profiles table name
Solution:
So u just need to do this: rename "user" table and name it numerically smaller than the "profiles" table.So problem will solve.
Other solution:
delete all migration files after run them respectively this commands.
php artisan make:migration create_users_table
php artisan make:migration create_profiles_table
Try this;
public function up()
{
Schema::dropIfExists('profiles');
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
That is the migration. Before you are able to run it; delete the row for 'CreateProfilesTable' in the migrations table.