Skip to content
Advertisement

Base table or view not found in laravel 6 when using validator

I belong to the reader gang and this happens to be my first question on SO. Pls, pardon me for mistake

I was trying to validate request in register function. Here is the code.

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email|unique:user',
        'password' => 'required',
        'c_password' => 'required|same:password',
    ]);

    if($validator->fails()) {
        return $this->sendError('Validation Error.', $validator->errors());
    }

    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')->accessToken;
    $success['name'] =  $user->name;

    return $this->sendResponse($success, 'User registered successfully.');
}

This is sendResponse method

public function sendResponse($result, $message)
{
    $response = [
        'success' => true,
        'data'    => $result,
        'message' => $message,
    ];

    return response()->json($response, 200);
}

This is sendError method

public function sendError($error, $errorMessages = [], $code = 404)
{
    $response = [
        'success' => false,
        'message' => $error,
    ];

    if(!empty($errorMessages)) {
        $response['data'] = $errorMessages;
    }

    return response()->json($response, $code);
}

Response I am getting

IlluminateDatabaseQueryException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nvrd_test.user' doesn't exist (SQL: select count(*) as aggregate from `user` where `email` = email@yahoo.com) in file /home/vagrant/code/nvrd/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 669*

Note: I have also tried to use public $table='users' to no avail.

I hope someone will come to rescue.

Also if i remove

if($validator->fails()) {
        return $this->sendError('Validation Error.', $validator->errors());
    }

it works good but not validation message is being returned

Advertisement

Answer

Tables are plural in Laravel by design. The unique rule is not based on a model, but the parameter you pass to it is the table name. So that parameter should be plural and therefor the validation should look like this.

'required|email|unique:users'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement