laravel db code example

Example 1: DB::transaction

use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');

    DB::delete('delete from posts');
});

Example 2: db import laravel

use Illuminate\Support\Facades\DB;

Example 3: laravel create db table

php artisan make:migration create_users_table

Example 4: laravel db inserr

DB::table('users')->insert([
    'email' => '[email protected]',
    'votes' => 0
]);

Example 5: DB::transaction

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

Example 6: TRANSACTON LARAVEL QUERY BUILDER

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

Tags:

Sql Example