Im using Laravel 4 with MySQL and I want to know how to control possible errors when a record is inserted, updated or deleted in DB. For example, if I do an update as follows:
DB::table('user')->where('id', $id)->update($userdata);
How could I know if that query fails? I thought of using a try-catch block to catch the exception and deal with it but I want to know whether there exists a Laravel specific method.
By default, when you use an Eloquent model's findOrFail in a Laravel 5 application and it fails, it returns the following error: ModelNotFoundException in Builder. php line 129: 'No query results for model [App\Model]'. So to catch the exception and display a custom 404 page with your error message like "Ooops"....
The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query: try { $results = \DB::connection("example") ->select(\DB::raw("SELECT * FROM unknown_table")) ->first(); // Closures include ->first(), ->get(), ->pluck(), etc. }
In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.
put it in a try catch block.
try {
DB::table('user')->where('id', $id)->update($userdata);
}catch(\Exception $e){
//Do something when query fails.
}
moreover,
DB::insert()
returns boolean.
DB::update()
returns boolean
DB::delete()
returns boolean
DB::insertGetId()
return the last inserted id.
You can write your follow up codes depending upon the value.
P.S. The above are not for errors but just to know whether your query affected some rows or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With