laravel db facade 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: TRANSACTON LARAVEL QUERY BUILDER

DB::beginTransaction();

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

Example 3: DB: in eloquent using sql

$results = DB::select('select * from users where id = :id', ['id' => 1]);

Example 4: Laravel DB facade relations

$antiques = DB::table('antiques')
    ->join('images', 'images.antiques_id', '=', 'antiques.id')
    ->latest()
    ->limit(20)
    ->get(['antiques.*', 'images.path']);

Tags:

Php Example