【问题标题】:Laravel index and store views are in the same page approachLaravel 索引和存储视图在同一页面方法中
【发布时间】:2019-11-28 19:24:47
【问题描述】:

我有一个查看帖子和添加帖子的页面。

在我的控制器中,我有两种返回同一页面的方法:

public function index () {
  return view('posts.index', [
    'posts' => Post::all()
  ]);
}

public function store (Request $request) {
  $validator = validate($request);

  if ($validator->fails()) {
    return view('posts.index', [
      'message' => $validator->messages(),
      'status' => '400'
    ]);
  } 

  $post = new Post;
  $post->title = $request->title;
  $post->body = $request->body;
  $post->user_id = 1;
  $post->save();

  return view('posts.index', [
    'message' => 'Successfully published post!',
    'status' => '200'
  ]);
}

现在在存储新帖子时,索引视图会丢失 index 方法中的帖子数据。这是否意味着在我的每次更新中,我都应该包含帖子变量?

public function store (Request $request) {
  $validator = validate($request);

  if ($validator->fails()) {
    return view('posts.index', [
      'message' => $validator->messages(),
      'status' => '400',
      'posts' => Post::all()
    ]);
  } 

  $post = new Post;
  $post->title = $request->title;
  $post->body = $request->body;
  $post->user_id = 1;
  $post->save();

  return view('posts.index', [
    'message' => 'Successfully published post!',
    'status' => '200',
    'posts' => Post::all()
  ]);
}

顺便说一句,我是 Laravel 的新手。

【问题讨论】:

  • 存储后不返回视图而是return redirect()->route(NAMEOFYOURINDEXROUTE)store() 方法不需要视图(update() 方法相同)。另外:laravel.com/docs/master/…
  • 啊啊啊好吧。谢谢你!抱歉,我没有看到 Laravel 文档的那部分内容。

标签: laravel


【解决方案1】:

通常,Controller 的 store()(以及 update()delete())方法不需要视图。当存储/更新/删除成功时,不显示视图,而是重定向到不同的路由。

替换

return view('posts.index', [
    'message' => 'Successfully published post!',
    'status' => '200'
  ]);

return redirect()
   ->route(NAMEOFYOURINDEXROUTE)
   ->with('message', 'Successfully published post!');

其中NAMEOFYOURINDEXROUTE 是您要重定向到的路由的名称。 (这可能是仪表板或产品列表/索引等 - 您决定)

有关重定向的更多信息:https://laravel.com/docs/master/redirects 并使用 Flash 消息重定向:https://laravel.com/docs/master/redirects#redirecting-with-flashed-session-data

编辑: 正如@user3532758 指出的,这里有一个链接值得一提:https://en.wikipedia.org/wiki/Post/Redirect/Get(基本上,重定向到不同的路由可以防止在浏览器中刷新页面时意外重新提交数据)

【讨论】:

  • 我认为值得一提的是P/R/G规则。
  • @user3532758 告诉我,什么是“P/R/G 规则”?
  • 发布/重定向/获取。 en.wikipedia.org/wiki/Post/Redirect/Get
  • @user3532758 好的,感谢您的链接,已将其添加到我的答案中
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 2013-08-10
  • 2018-09-18
相关资源
最近更新 更多