我正在laravel建立一个网站。 用户表有两个电子邮件字段,即“电子邮件”字段和“new_email”字段。当用户想要更改电子邮件时,它首先存储在“new_email”中,然后当用户确认更新“电子邮件”字段时。
一切都很好,但我希望在与'email'字段比较时将'new_email'字段限制为唯一。因此,没有用户可以将他的电子邮件更改为现有用户。我也会在php端进行检查,但我希望数据库限制它...所以我尝试了以下内容:
Schema::table('users', function ($table) {
$table->string('new_email')->unique('email')->nullable();
});
没有成功,我仍然可以在'新'字段中添加电子邮件,即使它是电子邮件中的alerady ..
那么,我怎样才能做到这一点?
答案 0 :(得分:0)
您可以使用Laravel中的Request轻松完成此操作,
/**
* Class ChangeEmailRequest
* @package App\Http\Requests
*/
class ChangeEmailRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
// Here it will check for unique in users table fro email field
return [
'new_email' => 'required | email |unique:users,email',
// Considering you have user Id while updating
'user_id' =>'required | numeric'
];
}
}
//在控制器中,您只需使用此请求,如下所示:
<?php namespace App\Http\Controllers;
use App\Http\Requests\ChangeEmailRequest;
/**
* Class User
* @package App\Http\Controllers
*/
class User extends Controller
{
public function changeEmail(ChangeEmailRequest $request)
{
// Considering you have user Id with it for updating
$userId = $request->input('user_id', null);
$user = User::findOrFail($userId);
$user->new_email = $request->input('new_email', null);
$user->save();
return response($user);
}
}