1. 程式人生 > >Laravel5 - 重定向 redirect 函數的詳細使用

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

UNC board 進行 輔助 並且 Once pan 其中 cep

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

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

  示例路由:

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

  示例動作:

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

1. 簡單的重定向

  假設我們當前的域名為:http://localhost

return redirect(‘home‘);

  重定向到 http://localhost/home

return redirect(‘auth/login‘);

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

return redirect(‘‘);

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

類實例。

2. 鏈接方法的重定向

return redirect()->back();

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

return back()->withInput();

3. 重定向到命名路由

// 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方法。

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

  如果要重定向到帶 ID 參數的路由(Eloquent 模型綁定),可以傳遞模型本身,ID 會被自動解析出來。

4. 重定向到控制器動作

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

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

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

  如果控制器路由要求參數,你可以將參數作為第二個參數傳遞給action方法。

5. 帶數據的重定向

  重定向到一個新的 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獲取這些數據。

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