【问题标题】:Laravel my post method (store) form not workingLaravel 我的发布方法(商店)表单不起作用
【发布时间】:2018-12-15 09:21:11
【问题描述】:

PostsController.php

 public function store(Request $request)
    {
 Post::create($request->all());
 return redirect('/posts');
}

我在帖子目录中的视图 create.blade.php

@extends('layout.app')



@section('content')

    <h1>Create Post</h1>

    <form action="/posts" method="post">

        <input type="text" name="title" placeholder="Enter title"> <!-- this name=title comes from create_posts_table -->
        {{--{{csrf_field()}}--}}
        <input type="submit" name="submit">

    </form>

@stop

路线

Route::resource('/posts','PostsController');

当我提交浏览器转到 localhost/posts 并显示:

Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404
localhost
Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.5

没有记录不会保存

【问题讨论】:

  • 您是否将文档根设置为/public
  • 这是唯一有此问题的路线吗?
  • @ChinLeung /posts/
  • @Nima 是的,更新也不起作用
  • 我认为@ChinLeung 的意思是您的 Apache 或 Web 服务器 DocumentRoot 是否设置为 Laravel 源代码中的 /public 文件夹?

标签: php laravel forms redirect store


【解决方案1】:

这有两个问题。

您正在使用资源路由,因此您需要适当地路由到 store 方法:

 <form action="{{ route('posts.store') }}" method="post">

此外,您需要欺骗其他控制器端点上的方法,例如 DELETE 方法,因为它会因 POST 请求而失败,您可以这样做:

<form action="{{ route('posts.delete') }}" method="post">
    @csrf
    {{ method_field('DELETE') }}

看看这里,我在这个视频https://youtu.be/kPYtJo7RyUQ 中介绍了这一点

【讨论】:

    【解决方案2】:

    试试:

    <form action="{{ route('posts.store') }}" method="post">
        //
    </form>
    

    或者您可以阅读this document 了解更多信息。请注意,您不能通过浏览器调用 url 发送发布请求。你可以为它提交一个表格

    【讨论】:

    • 我尝试了这个并修复了 url,但出现了这条消息:页面由于不活动而过期。请刷新并重试。
    • 我认为你应该检查 csrf 字段?
    • 发送一个 user_id 来存储。或者让它在迁移中可以为空
    • 非常感谢 Ehsan 和另一个问题:如何更改此 url 操作:
    • 你可以像这样向它传递数据:{{ route('posts.store', ['id' => $post->id] }}
    猜你喜欢
    • 2014-02-28
    • 2015-08-21
    • 1970-01-01
    • 2018-12-06
    • 2014-04-10
    • 1970-01-01
    • 2019-07-17
    • 2013-03-23
    • 2018-11-12
    相关资源
    最近更新 更多