我正在laravel建立一个网站。用户表有两个电子邮件字段,一个'email'字段和一个'new_email'字段。当用户想要更改电子邮件时,它首先存储在'new_email'中,然后当用户确认它更新'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'
];
}
}
//在控制器中,你必须像下面这样使用这个请求:
<?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);
}
}
参考:Laravel Request, Laravel Validation