调用函数保存和重定向路由:Laravel 5.2

Calling function to save and redirect route: Laravel 5.2

我在控制器中有以下功能。

public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
    $this->SaveChanges($request);
}

private function SaveChanges($request) {
    if($request['CountryID'] == 0) {
        $Country = new \App\Models\CountryModel();
    }
    else {
        $Country = \App\Models\CountryModel
                  ::where('CountryID', $request['CountryID'])->first();
    }

    $Country->Country = $request['Country'];
    $Country->CountryCode = $request['CountryCode'];
    $Country->save();
    return redirect()->route('AllCountries');
}

public function AllCountries() {
    $Countries = \App\Models\CountryModel::all();
    return view('Country.List', array('Countries' => $Countries));
}

问题在下一行:当我调用函数 SaveChanges 时,我无法看到国家列表页面,当我直接在 UpdateCountry 函数中编写代码时,它成功地重定向了路由。

return redirect()->route('AllCountries');

以前有人遇到过这个问题吗?

您的路线正在由 UpdateCountry 函数处理。 Laravel 将根据此函数的 returned 值采取行动。但是,您不会return从这个函数中获取任何东西。

您调用 SaveChanges,它 return 是一个 Redirect 对象,但是您 return 没有从您的 UpdateCountry 函数中得到任何东西。您需要 UpdateCountry 函数中的 Redirect 对象,以便 Laravel 实际上 return 重定向到客户端。

将您的 UpdateCountry 函数更新为:

// added the return statement, so this function will return the redirect
// to the route handler.
public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
    return $this->SaveChanges($request);
}

也许您在 $this->SaveChanges($request) 中遗漏了一个 return。它必须是:

public function UpdateCountry(\App\Http\Requests\CountryRequest $request) {
    return $this->SaveChanges($request);
}

希望它对你有用。