Skip to content

Commit

Permalink
Save visit data as mysqli bind
Browse files Browse the repository at this point in the history
  • Loading branch information
creator4ever committed Aug 22, 2021
1 parent b353206 commit 4aef194
Showing 1 changed file with 2 additions and 39 deletions.
41 changes: 2 additions & 39 deletions src/Traits/Visitable.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public function visit($ip = '')
$ip = request()->ip();
}

return self::insertOrUpdateVisit([
return $this->visits()->updateOrCreate(
[
'ip' => $ip,
'date' => Carbon::now()->toDateString(),
Expand All @@ -28,7 +28,7 @@ public function visit($ip = '')
'created_at' => now(),
'updated_at' => now(),
]
]);
);
}

/**
Expand Down Expand Up @@ -195,41 +195,4 @@ public function queryPopularBetween($query, $from, $to)
$query->whereBetween('date', [$from, $to]);
}])->orderBy('visits_count', 'desc');
}

public static function insertOrUpdateVisit(array $rows)
{
$table = 'visits';

$first = reset($rows);

$columns = implode(
',',
array_map(function ($value) {
return "$value";
}, array_keys($first))
);

$values = implode(
',',
array_map(function ($row) {
return '(' . implode(
',',
array_map(function ($value) {
return '"'.str_replace('"', '""', $value).'"';
}, $row)
) . ')';
}, $rows)
);

$updates = implode(
',',
array_map(function ($value) {
return "$value = VALUES($value)";
}, array_keys($first))
);

$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";

return DB::statement($sql);
}
}

0 comments on commit 4aef194

Please sign in to comment.