I'm using Laravel 5.5. I've my database ready and i have 2 tables. 1) users
2) users_auth_tokens
There's no any data filled in users
table right now.
So, my requirement is for first time any third user call api to get refreshToken
for android device and i will insert data('auth_token'
, 'refresh_token'
, 'token_validity'
) into users_auth_tokens
table when it called. There's one field user_id
which i want to insert '0'
for first time api call and when any user make call api after login, i want to update same record(which is user_id=0
) with the logged-in user_id
.
But unfortunately, when i was trying to insert record with user_id=0
it's give me error like:
"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
tracker
.users_auth_tokens
, CONSTRAINTusers_auth_tokens_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
) ON DELETE CASCADE) (SQL: insert intousers_auth_tokens
(auth_token
,validity
,refresh_token
,updated_at
,created_at
) values (ETZEI11RY3D7RQE4XR6OBTNQHC6Q1ND187E5FD3E45281D3385D784C3D89C0697D46DDC, 1524135471, b87c88fdcf1eea0a6680620d8da77e4f0ee18b78, 2018-04-19 10:52:51, 2018-04-19 10:52:51))"
I know that why this error occurs because there's foreign key user_id
in users_auth_tokens
and there's no any record in users
table right now! I've tried with default 0 value from migration and make it nullable also, but no luck.
Anyway i want to insert user_id=0
in that table. I search some tricks on google but no one helps.
My code is like:
$usersAuthTokens = new UsersAuthTokens;
$usersAuthTokens->auth_token = $authToken;
$usersAuthTokens->validity = $time;
$usersAuthTokens->refresh_token = $newRefreshToken;
$usersAuthTokens->user_id = 0; //error is here..because no record in users table right now
$usersAuthTokens->save();
Anyone have an solution for this? Any helps will be appreciated!!
Thanks.