Cant create a user using Laravel framework - php

I am using Laravel 4 and the following code suffers from a bug that i am not being able to find it :(
So i require your help.
One of the part of my code (that gives me the error) is shown here:
if($status == 'admin')
{
$role_id = 1;
}
else
{
$role_id = 2;
}
$check_role = DB::table('roles')->where('id', $role_id)->pluck('id');
if(($password == $repeat_password)&&($check_role != 0)&&($first_name != "")&&($last_name != ""))
{
$user = User::create(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));
return View::make('pages/manageUsers')->with('info', 'Success!');
}
else
{
return View::make('pages/manageUsers')->with('info','Failed!');
}
I want to make you sure that roles table exists and it hase two rows (id =1 is admin, and is=2 is user).
The following error is shown:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`leaves_db`.`users`, CONSTRAINT `users_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`)) (SQL: insert into `users` (`username`, `password`, `first_name`, `last_name`, `no_total_leaves`, `active`, `updated_at`, `created_at`) values (demo .demo, y$BuTWHRpfPl.OztGhTltjteqvGZZ6xcbzlAnCgwrZYRxRDxB.fuqHe, demo , demo, 0, 1, 2015-01-12 11:35:55, 2015-01-12 11:35:55))

As per above mentioned code, you are not inserting value of column role_id in table USERS.
Bare in mind that column role_id in table USERS is foreign key of column ID on table ROLES. So It should always be included in your every insert statement.
$user = User::create(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));

It seems the query that is running is not actually inserting the role_id. I cannot see it in the query that the error shows.

Thanks for your support. I needed to use this row instead:
DB::table('users')->insert(array('username' => $username, 'password' => Hash::make($password), 'first_name'=>$first_name, 'last_name' => $last_name, 'no_total_leaves' => $no_total_leaves, 'active' => $active, 'role_id' => $role_id));

Related

$wpdb->insert() throws "foreign key constraint fails" error

I have the following code:
$chck = $wpdb->insert( 'poruke_viber', array(
'id' => $data['message_token'],
'tekst' => $messageText,
'primljena' => '1',
'user_id' => $user['id'],
'vrijeme_epoch' => $data['timestamp']
));
logData($wpdb->last_error);
and it throws error:
Cannot add or update a child row: a foreign key constraint fails
It bugged me for couple of hours, I checked that I already have user_id in my parent table, and everything.
Until I tried replacing insert with query.
So when I did:
$wpdb->query('INSERT INTO poruke_viber (id, tekst, primljena, user_id, vrijeme_epoch)
VALUES ("'.$data['message_token'].'","'.$messageText.'","1","'.$user['id'].'","'.$data['timestamp'].'")');
It worked like a charm!
I'm here with the working code but not understanding what happened.
Is it wrong to use $wpdb->insert() on a table that has a foreign key?

Laravel inserting by relationship to composite key table

I have these tables currently:
User table
id (primary key), name, email
User Model
protected $fillable = ['name', 'email'];
protected $visible = ['id','name','email'];
//Relationship
public function customAttributes()
{
return $this->hasMany('App\Models\UserAttribute');
}
UserAttribute Table
user_id, attribute_id, value //user_id and attribute_id is a composite key, both foreignkeys acting as primary keys establishing an unique combination
UserAttribute Model
protected $fillable = ['user_id', 'attribute_id','value'];
protected $visible = ['user_id', 'attribute_id','value'];
I'll use the following example to explain the issue:
$user = $this->user->create(['name' => 'admin', 'email' => 'admin#admin.com']);
//This works
$user->customAttributes()->save(new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']));
//This does not work
$user->customAttributes()->create([new \App\Models\UserAttribute(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1'])]);
I could just repeat the save for every custom that I want since it works, but I'm trying to figure out why create doesn't work.
The error I'm getting when I use create is (and yes, I've checked the record exists in the table that isn't listed here):
Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`user_attributes`,
CONSTRAINT `user_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`))
This is the query it's trying to execute:
insert into `user_attributes` (`user_id`) values (1)
I'm just curious at why this doesn't work with create, I'm not sure if it's something related to this specific scenario (create to a composite key table by relationship). It's somewhat ignoring the value and attribute_id field in the query that is executing
try this:
$user->customAttributes()->create(['user_id' => $user->id, 'attribute_id' => 1, 'value' => 'Just a custom1']);
customAttributes() already returns you instance of UserAttribute model, you don't need to enject that dependency when you use create() method via that relation
your query should be like below;
$user->customAttributes()->insert([
[
'user_id' => $user->id,
'attribute_id' => 1,
'value' => 'Just a custom1'
],
[
'user_id' => $user->id,
'attribute_id' => 2,
'value' => 'Just a custom2'
],
]);

Despite having check getting Integrity constraint violation error

I'm on laravel 5.2 and I'm checking whether the combo of 3 ids exists or not in DB after that I'm updating or creating the record.
I have the unique key index on first_id, second_id, third_id field. Still, occasionally I'm getting: Integrity constraint violation: 1062 Duplicate entry '103797-5371-D8BTmX0GAi' for key 'first_id'.
public function notification($fId, $sId, $tId)
{
$getEmail = Input::get('email');
$email = new Email($getEmail);
if(!$email->isValid()){
return Response::json(['error_message' => self::ERROR_MESSAGE_INVALID_EMAIL], 422);
}
$searchEmail = DB::table('newsletter')
->select('id', 'status', 'email')
->where(['first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId])
->first();
if($searchEmail){
$updateEmail = DB::table('newsletter')
->where(['first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId])
->update(['email' => $getEmail, 'deleted_at' => NULL, 'status' => 1, 'updated_at' => Carbon::now()]);
if($updateEmail){
return Response::json('Success',201);
}
}else{
$result = DB::table('newsletter')
->insertGetId(['email' => $getEmail, 'first_id' => $fId, 'second_id' => $sId, 'third_id' => $tId]);
if($result){
return Response::json('Success',201);
}
}
}
We have huge traffic and we get an error like this 5-6 times a week. Despite we have a check for record exists or not.
Is that can be DB sync issue? or is it something wrong with the code?

CODEIGNITER how to insert user_ID to mySQL when that user_ID is logged in

this is the error page
Cannot add or update a child row: a foreign key constraint fails (latihan_ci.adventure, CONSTRAINT adventure_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON UPDATE CASCADE)
INSERT INTO adventure (name, category, place, state) VALUES ('semeru', 'gunung', 'asa', 'asd')
and this is my controller
public function addTrip(){
$this->load->model('userModel');
$newTrip = ['name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'place' => $this->input->post('place'),
'state' => $this->input->post('state'),
];
$data['users'] = $this->userModel->getUserId()->result();
$this->db->insert('adventure',$newTrip);
$this->db->insert('adventure',$data);
redirect('userController/profile');
}
and this is my Model
public function getUserId()
{
return $this->db->get('users',['user_id']);
}
so how to add the user_ID to the mySQL when the value is user_ID that is already login..Thanks alot
when you are login at that time user_id store in session after use
controller
$newTrip = ['name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'place' => $this->input->post('place'),
'state' => $this->input->post('state'),
'user_id'=>$this->session->userdata('userdata'),
];

Integrity constraint violation: 1452 Cannot add or update a child row: laravel 5 error

i have a table employes and table contact in table employes there it a column called contactid witch is foreghn key to id in contact table when i create data in employes i gate intergrity constraints violation but i impute correct id.
here is my controller to handle create employes
public function create()
{
return view('employmentform');
}
public function handleCreate(Request $request)
{
$employe = employe::create([
'fname' => $request->input('first_name'),
'lname' => $request->input('last_name'),
'phone' => $request->input('phone_number'),
'email' => $request->input('email'),
'houseno' => $request->input('house'),
'kebele' => $request->input('kebele'),
'city' => $request->input('city'),
'state' => $request->input('state'),
'age' => $request->input('date'),
'username' => $request->input('user_name'),
'sex' => $request->input('sex'),
'password' => Hash::make($request->input('country')),
'salary' => $request->input('salary'),
'bankaccount' => $request->input('account'),
'bankname' => $request->input('bank'),
'employedate' => getdate(),
'contactid'=> 5,
]);
return Redirect::action('ContactController#create');;
}
i have a row with id 5 in contact table but i get error like this
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`shop1`.`employes`, CONSTRAINT `employes_contactid_foreign` FOREIGN KEY (`contactid`) REFERENCES `contacts` (`id`) ON DELETE CASCADE) (SQL: insert into `employes` (`fname`, `lname`, `phone`, `email`, `houseno`, `kebele`, `city`, `state`, `age`, `username`, `sex`, `password`, `salary`, `bankaccount`, `bankname`, `updated_at`, `created_at`) values (eu, tseu, 0912378909, eualtse#gmail.com, hdikw, sdo, sjad, jaos, 2007-09-09, euael, Female, y$VhU2iJSuXAoXqsan38Gsve5JGtahhNeYpzeJjAYRnTGAEI1TeBCaK, 3000, 9839408, enb, 2015-05-16 13:07:09, 2015-05-16 13:07:09))
my table schema
Schema::table('employes', function($table)
{
$table->integer('contactid')->unsigned();
$table->foreign('contactid')->references('id')->on('contacts');
});
You are entering value 5 for contactid which is a froeign key in your employees table and primary key in contact table as id. Now you are entering a constant value into employee table irrespective of the fact whether you have id 5 in contact table or not. By looking at the error it is clear that you do not have an entry in contact table where id is 5.

Categories