The following is the tutorial column of Laravel to introduce you to Laravel view view() and redirection redirect(). I hope it will be helpful to friends who need it!
1. Use of view()
Simple return to the view
// 所传的参数是blade模板的路径 // 如果目录是 resources/views/static_pages/home.blade.php 则可以使用 return view('static_pages/home'); 或 return view('static_pages.home');
Pass data to the view
$title = 'Hello Laravel'; $user = User::find(1); // view() 的第二个参数接受一个数组 return view('static_pages/home', compact('user')); return view('articles.lists')->with('title',$title); // 所传递的变量在blade模板中用 {{ $title }} 或 {!! $title !!} 输出 // 前者作为文本输出,后者作为页面元素渲染
2. Use of redirect()
Url-based redirection
// 假设我们当前的域名为:http://localhost 则重定向到 http://localhost/home return redirect('home');
Route-based redirection
return redirect()->route('home');
Controller-based redirection
return redirect()->action('UserController@index')
Transfer data
return redirect('home')->with('title', 'Hello Laravel'); // 将表单值保存到 Session 中,可以用 {{ old('param') }} 来获取 return redirect('home')->withInput(); // 接收一个字符串或数组,传递的变量名为 $errors return redirect('home')->withErrors('Error');
Other usage
// 返回登录前的页面,参数为默认跳转的页面 redirect()->intended(route('home')); // 返回上一个页面,注意避免死循环 redirect()->back();
3. Choice of using view() or redirect()
view( ) and redirect()
Using return view() will not change the currently visited url, return redirect() will change the currently visited url
Using return view() will not Invalidate the Flash of the current Session, but return redirect() will invalidate the Flash
In the RESTful architecture, it is recommended to use return view() when accessing the Get method, and return redirect() to access other methods
The above is the detailed content of Do you use Laravel view() and redirect()?. For more information, please follow other related articles on the PHP Chinese website!