Skip to content
Advertisement

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:

IlluminateDatabaseQueryException
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 AppHttpControllersAuth;

use AppHttpControllersController;
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;

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?

Advertisement

Answer

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'));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement