Search code examples
phpsqlsql-serverlaravelsyntax-error

Laravel - Conversion failed when converting date and/or time from character string


I'm using Laravel 9 and PHP 8.0. When I try to update a user, I get the following exception:

SQLSTATE[22007]: [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string.

I think the query being executed is internal to Laravel:

SELECT
  count(*) AS aggregate
FROM
  [ users ]
WHERE
  [ email ] = user_email
  AND [ id ] <> user_id
  AND [ deleted_at ] = NULL

user_email and user_id are the email and id of the user being updated.

I know that the issue here is because the query has incorrect syntax for SQL Server, it should be "[ deleted_at ] IS NULL" instead of "= NULL", but I don't know to fix it.

QueryException Stack Error


Solution

  • Thanks everyone. I was able to solve the issue thanks to Snapey at Laracast forum. The query was being executed because of the Laravel validation, but writing the validation like this generates the wrong query.

    'email' => 'required|email|string|max:255|unique:users,email,'.$this->id.',id,deleted_at,null',
    

    Changing it to this solves the issue:

    'email' => [
        'required',
        'email',
        'string',
        'max:255',
        Rule::unique('users')
                ->ignore($this->id)
                ->where(fn (Builder $query) => $query->whereNull('deleted_at' ))],
    

    I'm not sure if this is an issue with Laravel or if it's intended to work like this, but I think the simplified way should work as well and generate the right query.