【问题标题】:Prevent creating multiple entries with Laravel 4防止使用 Laravel 4 创建多个条目
【发布时间】:2014-09-18 10:13:55
【问题描述】:

快速点击提交按钮时如何防止多次提交?

这是我的store 函数:

public function store()
{
    $input = Input::except('_token');
    $country = new Country($input);

    $country->save();
}

我考虑过为唯一 ID 添加验证。但我认为,如果相同的方法多次执行,每个Country 实例会有所不同,因此会有不同的 id,所以无论如何都会创建条目。我不喜欢在这种情况下使用验证的想法。

我有一些东西可以防止在更新实体时多次提交:

public function updatePost(Post $post) {
    if (count($post->getDirty()) > 0) {
        $post->save();
        return Redirect::back()->with('success', 'Post is updated!');
    } else {
        return Redirect::back()->with('success', 'Nothing to update!');
    }
}

但是,getDirty() 在存储新实体时没有任何帮助。

我已经搜索了一段时间,但没有直接找到任何东西。

处理这个问题的常用方法是什么?

编辑。尝试使用Redirect::route(),但我得到了相同的结果。

【问题讨论】:

  • 我看到了,但没有帮助。
  • 答案中有一条评论说答案中的选项不是选项。 Session::put('_token', sha1(microtime()))Redirect::route('form/success')->with("data", $myData) 都需要完成。而且你需要在store()的开头顺便做Session::put('_token', sha1(microtime()))
  • 为什么不能使用其他stackoverflow的方法?保存数据库的IP/时间。如果同一个IP在预定时间内请求另一个条目,则拒绝它

标签: laravel laravel-4


【解决方案1】:

我认为您可以/应该在这里考虑多种方法的组合。

首先,我肯定会说,可以应用强制唯一性的模型规则来保护您应用的数据完整性。

其次,为了从一开始就防止这种情况发生,您可能希望实现一个简单的 Javascript 函数,该函数会在单击后禁用提交按钮。

【讨论】:

  • 依赖 JavaScript 来处理这种事情是一个糟糕的主意,因为用户可以禁用它并且问题仍然存在
【解决方案2】:

这是我的方法:

public function store()
{
    $input = Input::except('_token');
    $host = gethostname();

    // Using -1 for $last_update will always ensure that the next line is true if no
    //   entry exists
    $last_update = Session::has($host) ? Session::get($host) : -1;

    // If no entry exists (-1), then the below statement will always be true!
    $allow_entry = (microtime() - $last_update) > $SOME_TIME;

    if ($allow_entry)
    {
        $country = new Country($input);
        $country->save(); 

        // Only update the Session if an entry was inserted
        Session::put($host) = microtime();
    }  
}

基本上,您使用Session,键是用户的hostname。并且值是进入的时间。

【讨论】:

    猜你喜欢
    • 2014-10-12
    • 2011-12-27
    • 1970-01-01
    • 2013-06-18
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2014-07-06
    相关资源
    最近更新 更多