dimanche 6 mai 2018

best way to identify sql errors while creating, updating or deleting a record in Laravel

I have this use case when I am saving a record after creating it and I want to check for errors, and inform my user of what happened on the sql server side without showing him the actual error message (if any occurs).

Here is what I came up with for the moment:

<?php
    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Book;
    use App\Http\Requests\BookRequest;
    use Illuminate\Database\QueryException;

    class BookController extends Controller {
        /* ... */

        public function store(BookRequest $request) {
            $book = new Book;

            $book->name = $request->input('name');
            $book->author = $request->input('author');
            $book->published_at = $request->input('publishDate');

            try {
                $book->save();
            }
            catch( QueryException $exception ) {
                $message = '';

                if( $exception->code == 23000 )  { // 23000: MySQL error code for "Duplicate entry"
                    $message = 'This book already exists.';
                }
                else {
                    $message = 'Could not store this book.';
                }

                return redirect()
                    ->back()
                    ->withInput()
                    ->withErrors($message);
            }

            return redirect()->route('book.index');
        }
    }
?>

The part where I hard code the MySQL error code bugs me and it is surely not portable.

Question

How are we supposed to identify database errors while saving/updating/deleting a record ?

Can we do this verification in a versatile way (database agnostic) ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire