仅在数据库中有数据时如何创建新用户-Laravel [英] how to create new user only if there is data in database-Laravel
问题描述
我已经完成了其他框架的编程工作,但这对我来说是新的,感谢您的进阶时间,我正在尝试创建新用户,条件是如果另一个表中有数据,那么将创建新用户,否则我已将我的代码放入if else语句中,并抛出错误.
I have done programming with other frameworks but this is new to me, thanks for your time in advanced, I'm trying to create new user on a condition that if there is data in another table then new user is created otherwise not I have put my code inside if else statement and is throwing errors.
下面列出了我用于创建新用户的功能:
my function for creating new user is listed below:
protected function create(array $data)
{
/*$exists = \DB::table('received_pay')->where('email', $data['email'])->first(); */
$exists=\DB::table('received_pay')->where('email', '=', $data['email'])->where('token', $data['token'])->exists();
if ($exists === null) {
// user doesn't exist
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}else{
return null;
}
}
}
推荐答案
默认情况下,您需要从RegisterController@create
方法返回User
实例,但不能返回null
.因此,请执行此操作,而不要使用return null;
:
You need to return User
instance from the RegisterController@create
method by default, you can't return null
. So, do this instead of return null;
:
return User::where('email', $data['email'])->first();
如果可以选择检查用户是否在users
表中,则可以使用firstOrCreate
方法:
If it's an option to check if the user exists in the users
table, you can use the firstOrCreate
method:
protected function create(array $data)
{
return User::firstOrCreate(['email' => $data['email'], [
'username' => $data['username'],
'password' => bcrypt($data['password']),
'token' => $data['token'],
]);
}
此外,如果要检查received_pay
表中是否存在用户,则可以保留原始的RegisterController@create
方法并将此规则添加到RegisterController@validator
方法中:
Also, you if want to check if a user exists in the received_pay
table, you can leave original RegisterController@create
method and add this rule to the RegisterController@validator
method:
'email' => 'unique:received_pay,email',
如果received_pay
表中已经存在具有相同电子邮件的用户,则这将不允许Laravel创建新用户.
This will not allow Laravel to create a new user if a user with the same email already exists in the received_pay
table.
这篇关于仅在数据库中有数据时如何创建新用户-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!