简体   繁体   English

如何使用 Laravel 表单验证检查提交到数据库的数据是否唯一?

[英]How to check if submitted data to a database is unique with Laravel form validation?

I am new to Laravel and I have run into an issue where when I check if data submitted is unique to a database is unique I get this error:我是 Laravel 的新手,我遇到了一个问题,当我检查提交的数据是否对数据库是唯一的时,我收到此错误:

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from `users` where `0` in (tom@heekdevelopment.comasd, asd) limit 1)
http://127.0.0.1:8000/register 

This is my code in Laravel:这是我在 Laravel 中的代码:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function index(){
        return view('auth.register');
    }
    
    public function store(Request $request){
        $this->validate($request, [
            'name'  => [
                'required',
                'max:255'
            ],
            'username' => [
                'required',
                'max:255',
                'unique:users,username'
            ],
            'email' => [
                'required',
                'email',
                'max:255',
                'unique:users,email'
            ],
            'password' => [
                'required',
                'confirmed'
            ]]);

        User::create([
            'name'      => $request->name,
            'username'  => $request->username,
            'email'     => $request->email,
            'password'  => Hash::make($request->password)
        ]);
        
        auth()->attempt([$request->only('email', 'password')]);
        
        return redirect()->route('dashboard');
    }
}

I thought the unique parameter checked if a value is unique or not.我认为unique参数检查一个值是否唯一。

It technically does check for it but when I submit a new value which is unique it throws the error, it does get entered into the database.它在技术上确实会检查它,但是当我提交一个唯一的新值时它会引发错误,它确实会输入到数据库中。

How to fix this?如何解决这个问题?

You should remove the additional array [] from the attempt method Since the only method of $request object return an array.您应该从attempt方法中删除附加数组[]因为$request object 的only方法返回一个数组。

auth()->attempt($request->only('email', 'password'));

Try like this像这样试试

'email' => [
            'required',
            'email',
            'max:255',
            'unique:users'
        ],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM