Hello @qaiswardag, what you are searching for are database transactions.
That means that you tell your database to only do everything or nothing in a set of queries.
Laravel has support build in: https://laravel.com/docs/9.x/database#database-transactions
For your code you get something like:
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
$product = Product::create([
'product_type' => 1,
'published' => $request->published,
]);
ProductEnglish::create([
'product_id' => $product->id,
'name' => $request->name,
'description' => $request->description,
]);
});
kikloo, faisal liked this reply
@tvbeek has given you the correct answer to your question but I request you to write the title of your problem that makes sense so that people will be able to help you in future as incorrect titles are always ignored by people.
tvbeek liked this reply
tvbeek, faisal liked this reply
Regarding Handling Deadlocks.
Why am I able to set an optional second argument which defines the number of times a transaction should be retried?
I mean the result will be the same.
Like below example with the number 5:
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
DB::update('update users set votes = 1');
DB::delete('delete from posts');
}, 5);
Also, what if the DB::transaction fails?
Is it possible to somehow give user an error message? Maybe inserting the DB::transaction in a try catch?
product model
public function productEnglish()
{
return $this->hasMany(ProductEnglish::class);
or
depending on your requirement
return $this->hasOne(ProductEnglish::class);
}
DB::transaction(function () {
$product = Product::create([
'product_type' => 1,
'published' => $request->published,
]);
$product->productEnglish()->create([
'name' => $request->name,
'description' => $request->description,
]);
});
Not 100%. I don't 100% get below code. Cause the retry will still give same result.
product model
public function productEnglish()
{
return $this->hasMany(ProductEnglish::class);
or
depending on your requirement
return $this->hasOne(ProductEnglish::class);
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community