How can I get a value between [] of a String?

0

When postgres sends an error, it sends a message with a code, example:

  

SQLSTATE [23505]: Unique violation: 7 ERROR: duplicate key violates uniqueness restriction «cargos_index_lower_unique»   DETAIL: The key already exists (lower (name :: text)) = (Engineer). (SQL: insert into "cargos" ("name", "updated_at", "created_at") values (ingeNiero, 2016-11-08 11:07:58, 2016-11-08 11:07:58) returning "id ")

How can I get the value of "SQLSTATE [23505]"? Is there a parameter for the Exception where I can do that? Or do I have to separate everything else manually?

    
asked by Pablo Contreras 08.11.2016 в 15:44
source

2 answers

1

Try the following example (that's ... an example):

    try
    {
        //aqui tu codigo que genera la exception
    }
    //atrapa la exception de sql
    catch(QueryException $e)
    {
        //...and do whatever you want
        return response()->view('my.error.view', [], 500);    
    }

QueryException inherits from PDOException which has the getCode method where the error code is. With that you would not have to pair any string.

It should work for you.

    
answered by 08.11.2016 / 15:53
source
1

One way to get that code from the string is by playing with the positions, a basic example:

$errorMsg = 'SQLSTATE[23505]: Unique violation: 7 ERROR: llave duplicada viola restricción de unicidad «cargos_index_lower_unique» ....';

$startPos = strpos($errorMsg, '[') + 1;

$endPos = strpos($errorMsg, ']');

$errorCode = substr($errorMsg, $startPos, $endPos - $startPos);
    
answered by 08.11.2016 в 15:59