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

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

Related

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

i wanna do php artisan db:seed, then i got this error " ErrorException array_merge(): Expected parameter 2 to be an array, int given"

I wanna make API Authentication Laravel Passport - Forgot and Reset Password with this source video on Youtube : https://www.youtube.com/watch?v=F9Xmc3iHc88&t=6s
My source Youtube use Laravel 6x, and i use Laravel 8x.
When i do step "seeding and factory database" in minute video 8:17 , i got
ErrorException array_merge(): Expected parameter 2 to be an array, int given
This is my error cmd
this is my UserFactory.php :
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\User;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'first_name' => $this->faker->firstName,
'last_name' => $this->faker->lastName,
'email' => $this->faker->unique()->safeEmail,
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
];
}
}
this is my UsersTableSeeder.php :
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
User::factory(App\Models\User::class, 10)->create();
}
}
and my DatabaseSeeder.php :
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UsersTableSeeder::class);
}
}
Can someone help me to explain why i got this error merge array?
Case Closed guys, in Laravel 8x u dont need type "
User::factory(App\Models\User::class, 10)->create();
just type :
User::factory(10)->create();
because u already call it User at first word..

I get this error when I try to register a new user. 'The department id must be an integer.'

I get this error when I try to register a new user: 'The department id must be an integer'. All the answers I'm receiving are helpful just that I get confused at times. So I've added more codes for clarification purposes. I have been battling around for some hours now. Here is the migration file.
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('department_id');
$table->integer('department_name');
$table->integer('department_code')->unique();
$table->text('department_discription')->nullable();
$table->tinyInteger('department_status')->default(1);
$table->softDeletes();
$table->timestamps();
This is the DepartmentController codes
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateDepartmentRequest;
use App\Http\Requests\UpdateDepartmentRequest;
use App\Repositories\DepartmentRepository;
use App\Http\Controllers\AppBaseController;
use Illuminate\Http\Request;
use Flash;
use Response;
class DepartmentController extends AppBaseController
{
/** #var DepartmentRepository */
private $departmentRepository;
public function __construct(DepartmentRepository $departmentRepo)
{
$this->departmentRepository = $departmentRepo;
}
/**
* Display a listing of the Department.
*
* #param Request $request
*
* #return Response
*/
public function index(Request $request)
{
$departments = $this->departmentRepository->all();
return view('departments.index')
->with('departments', $departments);
}
/**
* Show the form for creating a new Department.
*
* #return Response
*/
public function create()
{
return view('departments.create');
}
/**
* Store a newly created Department in storage.
*
* #param CreateDepartmentRequest $request
*
* #return Response
*/
public function store(CreateDepartmentRequest $request)
{
$input = $request->all();
$department = $this->departmentRepository->create($input);
Flash::success('Department saved successfully.');
return redirect(route('departments.index'));
}
/**
* Display the specified Department.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$department = $this->departmentRepository->find($id);
if (empty($department)) {
Flash::error('Department not found');
return redirect(route('departments.index'));
}
return view('departments.show')->with('department', $department);
}
/**
* Show the form for editing the specified Department.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$department = $this->departmentRepository->find($id);
if (empty($department)) {
Flash::error('Department not found');
return redirect(route('departments.index'));
}
return view('departments.edit')->with('department', $department);
}
/**
* Update the specified Department in storage.
*
* #param int $id
* #param UpdateDepartmentRequest $request
*
* #return Response
*/
public function update($id, UpdateDepartmentRequest $request)
{
$department = $this->departmentRepository->find($id);
if (empty($department)) {
Flash::error('Department not found');
return redirect(route('departments.index'));
}
$department = $this->departmentRepository->update($request->all(), $id);
Flash::success('Department updated successfully.');
return redirect(route('departments.index'));
}
/**
* Remove the specified Department from storage.
*
* #param int $id
*
* #throws \Exception
*
* #return Response
*/
public function destroy($id)
{
$department = $this->departmentRepository->find($id);
if (empty($department)) {
Flash::error('Department not found');
return redirect(route('departments.index'));
}
$this->departmentRepository->delete($id);
Flash::success('Department deleted successfully.');
return redirect(route('departments.index'));
}
}
here is the department code
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Departments
* #package App\Models
* #version September 21, 2020, 4:31 pm UTC
*
* #property integer $department_name
* #property integer $department_code
* #property string $department_discription
* #property boolean $department_status
*/
class Departments extends Model
{
use SoftDeletes;
public $table = 'departments';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'department_name',
'department_code',
'department_discription',
'department_status'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'department_id' => 'integer',
'department_name' => 'integer',
'department_code' => 'integer',
'department_discription' => 'string',
'department_status' => 'boolean'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
'department_name' => 'required|integer',
'department_code' => 'required|integer',
'department_discription' => 'nullable|string',
'department_status' => 'required|boolean',
'deleted_at' => 'nullable',
'created_at' => 'nullable',
'updated_at' => 'nullable'
];
}
in your migration, try make 'department_id' the primary key declaratively:
$table->primary('department_id');
then (like sta said in the comment) in your Department model:
protected $primaryKey = "department_id";
or change it's name to just 'id'
you should create a depatment like this:
\App\Models\Department::create([
'department_name' => 1,
'department_code' => 1,
'department_discription' => 'first department',
'department_status' => 1
]);
don't forget to add columns name to fillable variable in your Department model
If I understand your question, you are going to need to change your department_id field in the db.
Create a new migration and for your department_id key, set it like this.
$table->unsignedBigInteger('department_id')->autoIncrement();
That should take care of your issue. What it will do is maintain the integrity of your db in the event that you need to add a relationship because it will create that field the same type as the id on other tables (unsignedBigInteger), but it will also autoIncrement the field.

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.

Phalcon DB Criteria in Model ORM

In Phalcon model is there a way to use SQL "IN" condition and other database criteria? For example, i want to execute this query in phalcon
SELECT user_fullname, user_email FROM tbl_users WHERE user_id IN (1,2,3,4,5)
I know you can use query builder but I want it to be ORM. I want a method in my model getUsersByIds($userIds, $columnsToSelect) that will accept an array of userids and columns that you want to fetch in the table.
See my model below
<?php
use Phalcon\Mvc\Model;
class User extends Model
{
/**
*
* #var integer
*/
public $user_id;
/**
*
* #var string
*/
public $user_email;
/**
*
* #var string
*/
public user_phone;
/**
*
* #var string
*/
public user_fullname;
public function initialize()
{ $this->hasMany('user_id','Store\Bag','user_id');
}
public function getSource()
{
return "tbl_user";
}
public function find($parameters = null)
{
return parent::find($parameters);
}
public function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
/**
* I want to execute this query in my model
* SELECT user_fullname,user_email from tbl_user where user_id IN (1,2,3,4,5);
*/
public function getUsersByIds($ids=array(), $columns=array())
{
if(!is_array($ids))
$ids = array($ids);
if(!is_array($columns))
$columns = array($columns);
...................................
.........................
..............
}
}
There are two ways of doing this:
Method 1: inWhere('columnName', array('columnValues'))
public function getUsersByIds(array $userIds, $columnsToSelect = '') {
return self::query()
->inWhere('id', $userIds)
->columns($columnsToSelect ?: '*')
->execute();
}
This one goes in your User model
Method 2: conditions => 'id IN ({ids:array})
User::find(['id IN ({ids:array})',
'columns' => $columnsToSelect,
'bind' => array('ids' => $userIds)]);
I am typing on my mobile, so there might be a typo in there.