到控制器的laravel路由被调用两次

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

我仍在学习laravel,并用v5.4.28创建了一个项目,并用dev v5.5进行了测试,两个版本都两次调用控制器,从而插入了2条记录。仅当我使用WAMP并访问http://localhost/laravel/public/test?test=123

时才会发生这种情况

如果我使用php artisan服务并访问此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
    }
}
php laravel wamp artisan
1个回答
0
投票

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

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

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

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

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