Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a query fails in Laravel 4?

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.

like image 213
Darwing Avatar asked Aug 24 '13 23:08

Darwing


People also ask

What is Laravel find or fail?

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"....

How does Laravel handle query exception?

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. }

What is query () in Laravel?

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.


1 Answers

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.

like image 147
itachi Avatar answered Sep 20 '22 02:09

itachi