Shahid Chaudhary
Shahid Chaudhary

Reputation: 948

Laravel DB update exception

Im trying to get exception if update method failed i just check this try catch block it dont return any exception because this project id do not exist in my database i have only about hundred records.

 try {
    $project =  DB::table('project')
                  ->where('prj_id',  '987654' )
                  ->update([
                    'prj_status' => 'open',
                    'prj_updated_date' => Carbon::now()
                  ]);

 }catch(\Exception $e){

     dd($e);
 }

Upvotes: 3

Views: 8003

Answers (3)

Calin Blaga
Calin Blaga

Reputation: 1373

$projects_updated = DB::table('project')
    ->where('prj_id',  '987654' )
    ->update([
        'prj_status' => 'open',
        'prj_updated_date' => Carbon::now()
    ]);

if($projects_updated) {
    // n rows updated, do something
}
else {
    // nothing updated
}

Upvotes: 0

rypskar
rypskar

Reputation: 2092

An update on none-existing row do not fail in SQL. If you run a query like UPDATE foo SET bar = 'foobar' WHERE 1 = 2; your database would be happy to do the job and report back 0 rows updated.

You will have to check the value of $project to see if the update did update any rows

Upvotes: 5

vsharper
vsharper

Reputation: 317

If you're using Laravel 5, use the model to dictate what will be stored in the DB eventually.

So, using your project model, you'll have something like:

$project = Project::findOrFail('987654')
    ->update([
        'prj_status' => 'open',
        'prj_updated_date' => Carbon::now()
    ]);

You'll get a not found exception if the id of what you're looking for doesn't exist.

Upvotes: 1

Related Questions