Home > PHP Framework > Laravel > body text

​Do you use Laravel view() and redirect()?

藏色散人
Release: 2020-11-10 14:41:19
forward
2843 people have browsed it

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');
Copy after login

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 !!} 输出
// 前者作为文本输出,后者作为页面元素渲染
Copy after login

2. Use of redirect()

Url-based redirection

// 假设我们当前的域名为:http://localhost  则重定向到 http://localhost/home
return redirect('home');
Copy after login

Route-based redirection

return redirect()->route('home');
Copy after login

Controller-based redirection

return redirect()->action('UserController@index')
Copy after login

Transfer data

return redirect('home')->with('title', 'Hello Laravel');
// 将表单值保存到 Session 中,可以用 {{ old('param') }} 来获取
return redirect('home')->withInput();
// 接收一个字符串或数组,传递的变量名为 $errors
return redirect('home')->withErrors('Error');
Copy after login

Other usage

// 返回登录前的页面,参数为默认跳转的页面
redirect()->intended(route('home')); 
// 返回上一个页面,注意避免死循环
redirect()->back();
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!