Laravel 5.1在事务块内重定向 [英] Laravel 5.1 redirect within a transaction block
问题描述
我在Laravel 5.1应用程序中有一组删除语句,这些语句已放入事务中.
I have a set of delete statements in my Laravel 5.1 application that I have put inside a transaction.
我有如下代码,并试图返回同一页面.但是我得到了一个空白页面.我的routes.php很好.
I had my code like the following and was trying to return to the same page. But I was getting a blank page. My routes.php is fine.
DB::transaction(function () use ($foo, $bar, $request)
{
// Delete from table abc
$deletedFoo = DB::delete('delete from abc where id = ' . $foo);
// Delete from table xyz
$deletedBar = DB::delete('delete from xyz where id = ' . $bar);
// Shows blank page
$request->session()->flash('changes_saved', 'Success! All your changes were saved.');
return back();
});
但是,如果我将返回星号放在DB :: transaction块之外,则效果很好.
However, if I put the return starement outside the DB::transaction block it works fine.
DB::transaction(function () use ($foo, $bar)
{
// Delete from table abc
$deletedFoo = DB::delete('delete from abc where id = ' . $foo);
// Delete from table xyz
$deletedBar = DB::delete('delete from xyz where id = ' . $bar);
});
// Goes back to the page with the message
$request->session()->flash('changes_saved', 'Success! All your changes were saved.');
return back();
在意识到需要将重定向置于事务之外之前,我尝试了各种尝试.但为什么?我是Laravel的新手,在这里有点困惑.
I tried various things before I realized I need to put the redirect outside the transaction. But why? I am new to Laravel and bit confused here.
推荐答案
您必须使用return这样:
You have to use return like this:
return DB::transaction(function () {
...
return back();
});
要了解它,我们来破坏代码:
To understand it let's break the code:
$transaction = function ($foo, $bar, $request)
{
// ...
return back();
}
return DB::transaction($transaction); // return is required here
除非将DB::transaction
调用返回给控制器类,否则不会返回它.因此,使用return这样:
Unless you return the DB::transaction
call to your controller class then it'll not be returned. So, use return like this:
public function controllerMethod()
{
return DB::transaction(...); // You must return
}
因此,只需将return
键放在您的DB::transaction(...)
之前.另外,最好从事务外部控制执行流,例如:
So, just put the return
keywork before your DB::transaction(...)
. Also, it would be better if you controll the execution flow from outside the transaction, for example:
$result = DB::transaction(function () use ($foo, $bar) {
// ...
return true;
});
if($result === true) {
return back();
}
这篇关于Laravel 5.1在事务块内重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!