下面由laravel教程欄目給大家介紹laravel視圖view()與重定向redirect(),希望對需要的朋友有所幫助!
一、 view() 的使用
簡單的返回視圖
//?所傳的參數(shù)是blade模板的路徑 //?如果目錄是?resources/views/static_pages/home.blade.php?則可以使用 return?view('static_pages/home'); 或 return?view('static_pages.home');
向視圖傳遞數(shù)據(jù)
$title?=?'Hello?Laravel'; $user?=?User::find(1); //?view()?的第二個參數(shù)接受一個數(shù)組 return?view('static_pages/home',?compact('user'));? return?view('articles.lists')->with('title',$title); //?所傳遞的變量在blade模板中用?{{?$title?}}?或?{!!?$title?!!}?輸出 //?前者作為文本輸出,后者作為頁面元素渲染
二、redirect() 的使用
基于 Url 的重定向
//?假設(shè)我們當(dāng)前的域名為:http://localhost??則重定向到?http://localhost/home return?redirect('home');
基于路由的重定向
return?redirect()->route('home');
基于控制器的重定向
return?redirect()->action('UserController@index')
傳遞數(shù)據(jù)
return?redirect('home')->with('title',?'Hello?Laravel'); //?將表單值保存到?Session?中,可以用?{{?old('param')?}}?來獲取 return?redirect('home')->withInput(); //?接收一個字符串或數(shù)組,傳遞的變量名為?$errors return?redirect('home')->withErrors('Error');
其他用法
//?返回登錄前的頁面,參數(shù)為默認(rèn)跳轉(zhuǎn)的頁面 redirect()->intended(route('home'));? //?返回上一個頁面,注意避免死循環(huán) redirect()->back();
三、使用 view() 或 redirect() 的選擇
view() 和 redirect() 的異同
使用 return view() 不會改變當(dāng)前訪問的 url , return redirect() 會改變改變當(dāng)前訪問的 url
使用 return view() 不會使當(dāng)前 Session 的 Flash 失效 ,但是 return redirect() 會使 Flash 失效
在 restful 架構(gòu)中,訪問 Get 方法時(shí)推薦使用 return view() ,訪問其他方法推薦使用 return redirect()
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END