laravel DB::statement code example

Example 1: db::statement in laravel

DB::statement('DROP TABLE users');
DB::statement('ALTER TABLE projects AUTO_INCREMENT=123');

Example 2: laravel sql query

use Illuminate\Support\Facades\DB;

$users = DB::select('select * from users');

foreach ($users as $user) {
    echo $user->name;
}

Example 3: TRANSACTON LARAVEL QUERY BUILDER

DB::beginTransaction();

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

Example 4: DB: in eloquent using sql

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

Tags: