Ayoub
Ayoub

Reputation: 3

How can I catch MySQL/MariaDB Exception in my laravel 9 project?

In my susbcribe form, I have the email field as an PK. I want to handdle exception error "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry".

How can I do it ? PS : I insert into the DB inside of my Controller

query :

if (isset($_POST['nom'], $_POST['prenom'], $_POST['email'], $_POST['cities'])) {
    $nom = request('nom');
    $prenom = request('prenom');
    $email = request('email');
    $ville = request('cities');
    DB::insert('insert into newsletter (nom, prenom, email, ville) values (?, ?, ?, ?)', [$nom, $prenom, $email, $ville]);
}

Upvotes: 0

Views: 314

Answers (1)

kjoedion
kjoedion

Reputation: 580

// put these at the top of the file with other imports
use Exception; 
use Illuminate\Support\Facades\Log;

try {
    DB::table('newsletter')->insert([
        'nom' => request('nom'),
        'prenom' => request('prenom'),
        'email' => request('email'),
        'ville' => request('ville'),
    ]);
} catch (Exception $exception) {
    // do whatever you want when exception happens
    Log::info($exception->getMessage());
}

Upvotes: 0

Related Questions