Laravel 5.1在事务块中重定向

问题描述 投票:3回答:1

我在Laravel 5.1应用程序中有一组删除语句,我已将其放入事务中。

我有我的代码如下,并试图返回到同一页面。但我得到一个空白页面。我的routes.php很好。

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();

});

但是,如果我将return语句放在DB :: transaction块之外,它可以正常工作。

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的新手,在这里有点困惑。

php laravel-5.1
1个回答
6
投票

你必须像这样使用return:

return DB::transaction(function () {
    ...
    return back();
});

为了理解它,让我们打破代码:

$transaction = function ($foo, $bar, $request)  
{
    // ...
    return back();
}

return DB::transaction($transaction); // return is required here

除非你将DB::transaction调用返回给你的控制器类,否则它不会被返回。所以,使用如下返回:

public function controllerMethod()
{
    return DB::transaction(...); // You must return
}

所以,只需将qazxsw poi关键字放在qazxsw poi之前。此外,如果您从事务外部控制执行流程会更好,例如:

return
© www.soinside.com 2019 - 2024. All rights reserved.