0

this example code that works with database:

    $status = DB::table('post')->where('id', 2)->update([
        'title' => 'new title',
        'content' => 'new content'
    ]);

think $status = false means there was an problem in updating action. How can I show mysql error for DB class ?

1 Answer 1

2

Use Laravel's QueryException:

use Illuminate\Database\QueryException;

try {
    $status = DB::table('post')->where('id', 2)->update([
        'title' => 'new title',
        'content' => 'new content'
    ]);
} catch (QueryException $e) {
   //var_dump($e->getMessage())
   \Log::error('QueryException: ' . $e->getMessage())   
}

UPDATE: Why laravel throw QueryException when something wrong happened with SQL executing. See this Logic in laravel's source code.

Class: \Illuminate\Database\Connection

/**
 * Run a SQL statement and log its execution context.
 *
 * @param  string    $query
 * @param  array     $bindings
 * @param  \Closure  $callback
 * @return mixed
 *
 * @throws \Illuminate\Database\QueryException
 */
protected function run($query, $bindings, Closure $callback)
{
    $this->reconnectIfMissingConnection();

    $start = microtime(true);
    try {
        $result = $this->runQueryCallback($query, $bindings, $callback);
    } catch (QueryException $e) {
        $result = $this->handleQueryException(
            $e, $query, $bindings, $callback
        );
    }
    ......
}
Sign up to request clarification or add additional context in comments.

4 Comments

OP says $status = false, so the query was executed.
Mahdi, please explain how exactly this helped you and why did you have an exception.
Kevin, the question was addressed to Mahdi. He said that $status = false.
Oh I see, I misunderstood .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.