Laravel5:重定向 redirect 函數的詳細使用

Laravel5 中新增了一個函數 redirect() 來代替 Laravel4 中 Redirect::to() 來進行重定向操做。函數 redirect() 能夠將用戶重定向到不一樣的頁面或動做,同時能夠選擇是否帶數據進行重定向。

重定向響應是Illuminate\Http\RedirectResponse類的實例,其中包含了必須的頭信息將用戶重定向到另外一個URL。輔助函數redirect返回的就是RedirectResponse類的實例。php

示例路由:web

Route::get('testRedirect', 'UserController@testRedirect');

示例動做:session

public function testRedirect()
{
    // 如下示例代碼爲此處實現
}

簡單的重定向

假設咱們當前的域名爲:http://localhostapp

return redirect('home');

重定向到 http://localhost/homeide

return redirect('auth/login');

重定向到 http://localhost/auth/login函數

return redirect('');

重定向到 http://localhost,注意此處傳入的是一個空字符串,而不是什麼都不傳,上文已說 redirect() 返回Illuminate\Http\RedirectResponse類實例。spa

連接方法的重定向

return redirect()->back();

重定向到上一個 URL,須要注意死循環的問題。輔助函數back返回前一個 URL (使用該方法以前確保路由使用了web中間件組或者都使用了session中間件)。還有另一種方式:code

return back()->withInput();

重定向到命名路由

// get('login', ['as' => 'userLogin', 'uses'=>'loginController@index']);
return redirect()->route('userLogin');

重定向到命名爲 userLogin 的路由。這種方式的使用更爲靈活,由於咱們未來要修改 URL 結構,只須要修改 routes.php 中路由的配置就好了。中間件

// For a route with the following URI: profile/{id}
return redirect()->route('profile', [1]);

若是路由中有參數,能夠將其做爲第二個參數傳遞到route方法。blog

return redirect()->route('profile', [$user]);

若是要重定向到帶 ID 參數的路由(Eloquent 模型綁定),能夠傳遞模型自己,ID 會被自動解析出來。

重定向到控制器動做

return redirect()->action('HomeController@index');

只需簡單傳遞控制器和動做名到action方法便可。記住,你不須要指定控制器的完整命名空間,由於 Laravel 的RouteServiceProvider將會自動設置默認的控制器命名空間。

return redirect()->action('UserController@profile', [1]);

若是控制器路由要求參數,你能夠將參數做爲第二個參數傳遞給action方法。

帶數據的重定向

重定向到一個新的 URL 並將數據存儲到一次性 Session 中一般是同時完成的。

return redirect('dashboard')->with('status', 'Profile updated!');

此代碼會將數據添加到Flash會話閃存數據中,而後你能夠在結果 Controller 或視圖中使用該數據:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

用戶重定向到新頁面以後,你能夠從 Session 中取出顯示這些一次性信息。

Reminder: Session Flash Data
Laravel has a concept of Session Flash data for only one request – after the next is loaded, that Session element/value is deleted, and can’t be retrieved again. This is exactly what is happening in with() method – its purpose is to add an error message or some input data only for that particular redirect and only for one page. It does the same thing as a function Session::flash(‘error’, ‘Something went wrong.’).

Laravel 只有一個請求會話Flash數據概念,在下一個請求被加載後,會話數據被刪除,而且沒法再次檢索。

return redirect()->back()->withInput();

此方法沒有參數,它的做用是將舊錶單值保存到 Session 中。在新頁面你可使用old獲取這些數據。

相關文章
相關標籤/搜索