简体   繁体   中英

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:

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:

<?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.

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.

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

Try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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