我正在用 laravel 构建一个网站。 用户表有两个电子邮件字段,一个“电子邮件”字段和一个“新电子邮件”字段。当用户想要更改电子邮件时,它首先存储在“new_email”中,然后当用户确认时更新“电子邮件”字段。
很好,但我想限制“new_email”字段与“email”字段相比是唯一的。这样任何用户都不能将他的电子邮件更改为现有用户。我也会在 php 端进行检查,但我希望数据库对其进行限制。所以我尝试了以下操作:
Schema::table('users', function ($table) {
$table->string('new_email')->unique('email')->nullable();
});
没有成功,我仍然可以将电子邮件添加到"new"字段,即使它已经在电子邮件中了..
那么,我该如何实现呢?
最佳答案
你可以在 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'
];
}
}
//在 Controller 中你必须像下面这样使用这个请求:
<?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);
}
}
关于php - Laravel 数据库不同字段之间的唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32320788/