gpt4 book ai didi

php - 到 Controller 的 laravel 路由被调用两次

转载 作者:行者123 更新时间:2023-12-02 03:52:33 25 4
gpt4 key购买 nike

我仍在学习 laravel,并使用 v5.4.28 创建了一个项目,还使用 ​​dev v5.5 进行了测试,这两个版本都调用了 Controller 两次,从而插入了 2 条记录。只有当我使用 WAMP 并访问 http://localhost/laravel/public/test?test=123 时才会发生这种情况

如果我使用 php artisan serve 并访问它 http://127.0.0.1:8000/test?test=123它只插入一次

如果我使用 chrome 检查并查看我的网络选项卡,我会看到该页面在 wamp 上被调用了两次。

这正常吗?

将我的 routes/web.php 编辑为

Route::get('/', function () {
return view('home');
});
Route::get('/test', 'testController@store');

并创建了一个 testController

class testController extends Controller
{
public function store()
{
$test = new Test;
$test ->user_id = request('test');
$test ->save();

//if i put a redirect here then it wont insert twice
}
}

最佳答案

如果您有一个中间件对 next 进行两次调用,也会发生这种情况。例如,假设您有一个父中间件的句柄函数:

public function handle($request, Closure $next, ...$guards){
// Your logic here
return $next($request);
}

现在,假设您有一个子中间件,如下所示:

public function handle($request, Closure $next, ...$guards){
// Note this call to the parent's next
$resp = parent::handler($request, $next, $guards);
// Extra logic here
// ... and now we make another call to next
return $next($request);
}

为避免这种情况,请确保您在中间件的句柄函数中只调用了一次 next

https://laracasts.com/discuss/channels/laravel/controller-methods-called-twice-causing-duplicate-database-entries

关于php - 到 Controller 的 laravel 路由被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com