how to make multiple delete or update or insert in one transaction in yii2 using active records - activerecord

is it the right way in my code to do multiple statement in one transaction using active records?
cause I don't know how to make it like that
please advice, thanks

$transaction = Yii::$app->db->beginTransaction();
try {
//.... active record operations
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
Note from Yii2 doc: in the above code we have two catch-blocks for compatibility with PHP 5.x and PHP 7.x. \Exception implements the \Throwable interface since PHP 7.0, so you can skip the part with \Exception if your app uses only PHP 7.0 and higher.
References:
https://www.yiiframework.com/doc/api/2.0/yii-db-transaction
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#transactional-operations

Related

Backup failed in Browser, works with php artisan backup:run

I am new to Laravel, I have created a driver with the create function to create backups to my database on xampp server, but my problem is that in the browser it does not show me any errors but no backup of my database is created. Help me please. Here I leave the code of my create function.
public function create()
{
try {
// start the backup process
Artisan::call('backup:run', ['--only-db'=> true,'--disable-notifications'=> true]);
$output = Artisan::output();
// log the results
Log::info("Backpack\BackupManager -- new backup started from admin interface \r\n" . $output);
// return the results as a response to the ajax call
Alert::success('Nuevo Backup Creado');
return redirect()->back();
} catch (Exception $e) {
Flash::error($e->getMessage());
return redirect()->back();
}
}
Artisan::call('backup:run'); does not work use queue instead of call
working syntax
Artisan::queue('backup:run');

Return flash message if duplicate id on database

I want to create if else on controller laravel. if no error on database, data insert and return flash message success, and if have error on database (duplicate id) return error message i use laravel 5.3
This is exactly what I want
its my code
you can do try-catch with DB Transaction
try {
DB::beginTransaction();
// your code
// redirect with success message
DB::commit();
}catch (Exception $e) {
DB::rollback();
// other actions
// redirect with error message
}

Lumen transactions

I'am struggeling to get the transactions at work with laravel lumen, but still no success.
I see alot of DB facade for the transactions, but is there a way that I can use something like this?
There is no clear documentation about transactions in Lumen.
app('db')->transaction(function() {
// DB work
});
Thanks in advance
We can use the closure approach to using transactions. If the closure throws an exception it will automatically be rolled back. if closure pass it will be committed. hope this helps.
app('db')->transaction(function() {
// DB work
});
yes, here is the proper way to perform you Db transactions in Lumen.
DB::beginTransaction();
try
{
DB::commit();
}
catch (\Exception $e)
{
DB::rollback();
}`
in try before DB::commit(); you can add your code . once all good it will save to db and if any exception occurs it will rollback and will not save data.
Enjoy !
Happy Coding

Lumen QueryException write to log

I'm using Lumen 5.3.* and I need to make QueryException write errors on the storage/logs/lumen.log.
Other validations are writing to the log file except for QueryException.
try {
// throw here exception here
} catch (QueryException $e) {
// do what ever
} catch (CustomException $e) {
// do what ever
}
I have my CustomException extended to \Exception and use Handler class to to do report() as to why I am able to write to the log file. But the QueryException does not. (QueryException is a lumen vendor file)
I know it is possible to just to \Log() upon catch on the QueryException but I want to make things cleaner by not putting it this way.
Is there another way to do this aside from doing what was stated above?
Thanks in advance!

Throwing errors in Laravel

In my package, before I perform a query on my database I check if some of the params provided are valid:
//check
if(!$this->checkId($id)) //error
//do the query
$user = User::find($id);
What's the best way to handle this in a laravel package?
Throw an error? If so, which kind? Do an app abort?
Using findOrFail()
There is a pretty good method that Laravel provides just for this case called findOrFail().
What you can do is use that and then catch the exception.
try {
$user = User::findOrFail($queryParam);
} catch(ModelNotFoundException $e) {
// Do things that should happen here if your query parameter does not exist.
}
If you do not wish to catch it here, you can setup a listener for this exception. You can place it anywhere you wish as long as it's being autoloaded.
use Illuminate\Database\Eloquent\ModelNotFoundException;
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
Throwing an exception
If all you want to do is throw an error if a query param isn't available, you can throw any of the exceptions found here... https://github.com/symfony/symfony/tree/master/src/Symfony/Component/HttpKernel/Exception
If none suit you, you can create your own and just extend Symfony\Component\HttpKernel\Exception\HttpException and throw new YourCustomException($statusCode, $message);. Just follow what they've done in the other exception classes and it should be fairly easy.
Then you can modify the the "exception listener" to catch YourCustomException.
Here is a tutorial I found... http://fideloper.com/laravel4-error-handling
I would use Event Listeners for the most control.
Create an events.php in your app directory and include it in app/start/global.php
Or, you can register anywhere in your package.
Create a listener:
Event::listen('paramCheck.noId', function($id)
{
// do some logic, log something, return something, throw an error...
});
Then fire the event from whenever you need to:
if(!$this->checkId($id))
$returnFromEvent = Event::fire('paramCheck.noId', array($id));

Resources