MySQL create row error with php/laravel 8
Get the solution ↓↓↓I am trying to create a new row in 'my_groups' table, but am getting this error:
SQLSTATE[23000]: Integrity constraint violation:
1452 Cannot add or update a child row: a foreign key constraint fails
(mefirst.my_groups, CONSTRAINT my_groups_owner_id_foreign FOREIGN KEY (owner_id) REFERENCES users (id)
ON DELETE CASCADE)
(SQL: insert into my_groups (updated_at, created_at) values (2021-05-17 19:07:54, 2021-05-17 19:07:54))
Here is my schema:
Schema::create('my_groups', function (Blueprint $table) {
$table->id();
$table->string('groupName')->default('group');
$table->unsignedBigInteger('owner_id');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});
Here is my MyGroup model where I am creating the row and getting the error:
protected $fillable = [
'groupName',
'owner_id'
];
public static function add(User $user) {
$groupData = array('my group', $user->id);
Self::create($groupData);
return "success";
}
I have no idea why this is happening and I have confirmed the value of 'owner_id' does exist in my users table as many other solutions have suggested.
Answer
Solution:
The line$groupData = array('my group', $user->id);
is the problem.
array('my group', $user->id);
is the same as['my group', $user->id]
. There are no keys here. If you dumped$groupData
you'd get something like this.
array (
0 => 'my group',
1 => $user->id
)
When usingcreate()
, eloquent uses the keys to know which columns to fill. In this case, it's trying to fill the column'0'
with the'my group'
value and the column'1'
with$user->id
.
'0'
and'1'
are not in your$fillable
properties, which is why the resulting SQL (last line in your error) only seems to be inserting timestamps.
But even if'0'
and'1'
were in your$fillable
properties, SQL would throw another error about the tablemy_groups
having no such columns.
To fix this, simply add keys to your$groupData
array.
$groupData = [
'groupName' => 'my group',
'owner_id' => $user->id
];
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: string literal contains an unescaped line break
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.