在 Laravel 中,当你需要在请求中更新唯一的验证字段时,通常涉及到的是表单验证和模型关联。以下是一些基础概念、优势、类型、应用场景以及如何解决问题的详细解答。
假设我们有一个 User
模型,其中 email
字段需要保持唯一性。我们可以通过以下步骤来实现:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['name', 'email'];
public function scopeUniqueEmail($query, $email)
{
return $query->where('email', $email)->first();
}
}
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Models\User;
class UniqueEmail implements Rule
{
protected $user;
public function __construct(User $user = null)
{
$this->user = $user;
}
public function passes($attribute, $value)
{
if ($this->user && $this->user->email === $value) {
return true;
}
return !User::query()->uniqueEmail($value)->exists();
}
public function message()
{
return 'The :attribute must be unique.';
}
}
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\UniqueEmail;
use App\Models\User;
class UpdateUserRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$user = User::find($this->route('user'));
return [
'email' => ['required', 'email', new UniqueEmail($user)],
'name' => ['required', 'string', 'max:255'],
];
}
}
namespace App\Http\Controllers;
use App\Models\User;
use App\Http\Requests\UpdateUserRequest;
class UserController extends Controller
{
public function update(UpdateUserRequest $request, User $user)
{
$user->update($request->all());
return redirect()->back()->with('success', 'User updated successfully.');
}
}
通过以上步骤,你可以在 Laravel 请求中实现对唯一验证字段的更新和验证。
领取专属 10元无门槛券
手把手带您无忧上云