【问题标题】:Save unique visitor's ip and timestamp only in Laravel仅在 Laravel 中保存唯一访问者的 ip 和时间戳
【发布时间】:2023-01-14 08:50:48
【问题描述】:

一旦用户访问特定页面,我的应用程序将保存用户的 IP 和时间戳。

if (! auth()->check()) {
        $attributes = [
            'type' => 'Visited',
            'description' => 'The proposal was recently visited by someone with IP address '.\request()->getClientIp(),
            'ip' => \request()->getClientIp()
        ];

        (new ProposalLogController())->store($proposal, $attributes);
    }

以下是我如何使用 IP 存储所有详细信息:

public function store($proposal, $attributes)
{
    $proposalLog = new ProposalLog();
    $proposalLog->proposal_id       = $proposal->id;
    $proposalLog->event_type        = $attributes['type'];
    $proposalLog->event_description = $attributes['description'];
    $proposalLog->ip_address        = $attributes['ip'];
    $proposalLog->user_name         = $attributes['user']??'';
    $proposalLog->save();
}

当用户重新加载或刷新页面时,恰好再次保存了相同的 IP 和时间戳。防止提交相同的 IP 地址、时间戳或处理此问题的任何 Laravel 特定功能的最佳方法是什么?

【问题讨论】:

  • 显示您如何为用户存储 ips,ProposalLogController 如何链接到用户。
  • 使条目在某些情况下唯一,并在 ->store 行周围使用 catch try。
  • @KGG 我已经对发布添加的商店功能进行了更改。

标签: laravel


【解决方案1】:

一种方法是使用唯一的验证规则来防止保存重复的 IP 地址和时间戳。

$validatedData = request()->validate([
    'ip' => 'unique:proposal_logs,ip_address',
    'created_at' => 'unique:proposal_logs,created_at'
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2011-04-29
    • 2020-12-12
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多