Trying to make an API using Transaction() for making more security for database.
Code :
DatabaseName::transaction(function () {
$CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);
return $CheckExistingData;
});
Error :
BadMethodCallException in Builder.php line 2258:
Call to undefined method Illuminate\Database\Query\Builder::transaction()
Share your thoughts!
PostCustomer is MODEL
PostCustomer Model
class PostCustomer extends Model
{
protected $table = "Customer";
}
"Customer" is table name .
I tried something like this, try with this code
PostCustomer::beginTransaction();
try{
$result = true;
PostCustomer::commit();
}catch(Exception $exception)
{
PostCustomer::rollBack();
$errormsg = 'Database error!! ' . $exception->getMessage();
$result = false;
}
Transaction method will not work like this : See this https://laravel.com/docs/4.2/database#database-transactions.
Either you can use transaction method
or you may need to begin a transaction yourself
.
The problem is that transaction
method is available in Database\Connection and your model is an instance of Eloquent.
Therefore, PostCustomer
doesn't have the transaction method. You should call DB
(that's the facade that gives you access to Database\Connection
and the transaction
method.
You should do something like this:
DB::transaction(function () {
$CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);
return $CheckExistingData;
});
and import DB
facade of course.
Also you don't need a try/catch
expression:
Note: Any exception thrown within the transaction closure will cause the transaction to be rolled back automatically.
PS:
(only if you're using MySQL)
Probably using a transaction is not enough:
A SELECT
query inside a transaction, in itself, is not properly shielded from UPDATEs
and DELETEs
.
(source)