Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you an example of “Laravel begin transaction example”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.
First, what we’re doing here, This is the example :
Most developers don’t use Eloquent transactions in Laravel, imagine you have a product and product details table in the database, The product table has the name, price, location, etc, The product detail table has all the meta tags related to the product.
We also store the product id in the product details table as a foreign key.
When we add a new product or package we need to do two things, product data will be stored in the products table and product metadata will be stored in the product details table.
Our controller code is running well unless someone mistakes in the controller, Imagine a product is created successfully and the product meta details query fails for some reason.
You may use the transaction method provided by the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown.
If the closure executes successfully, the transaction will automatically be committed. You don’t need to worry about manually rolling back or committing while using the transaction method.
For those cases when we have multiple operations, depending on each other and can not fail individually.
To avoid those cases Laravel Provide Database Transaction, When if some of the action fails everything will be rollback automatically.
Generating Migration with Model :
php artisan make:model Package -m
php artisan make:model PackageDetail -m
Migration Structures :
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePackagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('packages', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('type');
$table->float('price');
$table->string('location');
$table->string('short_description');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('packages');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePackageDetailsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('package_details', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('package_id');
$table->string('meta_title');
$table->string('meta_description');
$table->string('meta_keywords');
$table->string('tags');
$table->softDeletes();
$table->timestamps();
$table->foreign('package_id')
->references('id')
->on('packages')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('package_details');
}
}
Run Migration :
php artisan migrate
app\Models\Package.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Package extends Model
{
use SoftDeletes;
use HasFactory;
protected $fillable = ['name', 'type','price','location','short_description'];
}
app\Models\PackageDetail.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PackageDetail extends Model
{
use SoftDeletes;
use HasFactory;
protected $fillable = ['package_id', 'meta_title', 'meta_description', 'meta_keywords', 'tags'];
}
Create a Controller :
php artisan make:controller PackageController
routes\web.php :
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PackageController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
#Databse Transaction Example
Route::get('/create-package', [PackageController::class, 'createPackage']);
Route::post('/store-package', [PackageController::class, 'storePackage'])->name('store.package');
app\Http\Controllers\PackageController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Package;
use App\Models\PackageDetail;
class PackageController extends Controller
{
public function createPackage()
{
return view('package.create');
}
public function storePackage(Request $request)
{
try{
\DB::beginTransaction();
#Create Product
$package = Package::create([
'name' => $request->package_name,
'type' => $request->package_type,
'price' => $request->package_price,
'location' => $request->package_location,
'short_description'=> $request->package_short_description
]);
#Create Product Details
$packageDetails = PackageDetail::create([
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'meta_keywords' => $request->meta_keywords,
'tags' => $request->tags,
'package_id' => $package->id,
]);
\DB::commit();
}
catch(\Exception $e){
\DB::rollback();
throw $e;
}
}
}
resources\views\package\create.blade.php
<main>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-10">
<div class="main">
<h3><a>How to use Database-Transaction in Laravel Eloquent | Example </a></h3>
<form method="post" action="{{route('store.package')}}">
@csrf
<div class="row">
<div class="form-group col-md-6">
<label>Package Name <span class="text-danger">*</span></label>
<input type="text" name="package_name" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Package Type <span class="text-danger">*</span></label>
<input type="text" name="package_type" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Package Price <span class="text-danger">*</span></label>
<input type="text" name="package_price" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Package Location <span class="text-danger">*</span></label>
<input type="text" name="package_location" class="form-control" required>
</div>
<div class="form-group col-md-12">
<label>Package short Description <span class="text-danger">*</span></label>
<textarea name="package_short_description" class="form-control" rows="4" cols="50" required></textarea>
</div>
</div>
<hr>
<div class="row">
<div class="form-group col-md-6">
<label>Meta Title <span class="text-danger">*</span></label>
<input type="text" name="meta_title" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Meta Description <span class="text-danger">*</span></label>
<input type="text" name="meta_description" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Meta Keywords <span class="text-danger">*</span></label>
<input type="text" name="meta_keywords" class="form-control" required>
</div>
<div class="form-group col-md-6">
<label>Tags <span class="text-danger">*</span></label>
<input type="text" name="tags" class="form-control" required>
</div>
</div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn btn-secondary">save</button>
</form>
</div>
</div>
</div>
</div>
</main>
Run Application :
http://127.0.0.1:8000/create-package
If some of the action fails everything will be rollback automatically using Database Transaction.
In this article, we learned “How to use Laravel begin transaction example”, I hope this article will help you with your Laravel application Project.
Read also:- Laravel Eloquent when example.