4 回答

TA貢獻1801條經驗 獲得超16個贊
嘗試使用Request::ip()獲取ip;
$ip = Request::ip();
對于 Laravel 5.4 +:
$ip = $request->ip();
// or
$ip = request()->ip();
而且我認為你可以使用中間件和redis來計算這個計數,這樣可以減少db的壓力。

TA貢獻1802條經驗 獲得超10個贊
在這種情況下,一個好的解決方案是創建一個middleware跟蹤所有用戶的。我們可以將任何類型的業務邏輯放在middleware.
<?php
namespace App\Http\Middleware;
use Closure;
class TrackUser
{
public function handle($request, Closure $next)
{
/* You can store your user data with model, db or whatever...
Here I use a repository that contains all my model queries. */
$repository = resolve('App\Repositories\TrackUserRepository');
$repository->addUser([
'ip' => request()->ip(),
'date' => now(),
]);
return $next($request);
}
}
然后添加middleware
到App\Kernel.php
:
$middleware
如果您希望它成為在每個請求上運行的全局中間件,請將其添加到。$middlewareGroups
如果您希望它僅在每個web
-route上運行,請將其添加到。$routeMiddleware
如果您想指定routes/web.php
何時應用中間件,請將其添加到。
您還應該考慮在middleware
“ try
catch
”-語句中移動任何邏輯,它將您的用戶因“跟蹤”-代碼引起的任何錯誤而停止的風險降到最低。
try {
$repository = resolve('App\Repositories\TrackUserRepository');
$repository->addUser([
'ip' => request()->ip(),
'date' => now(),
]);
} catch (\Exception $e) {
// Do nothing or maybe log error
}
return $next($request);

TA貢獻1776條經驗 獲得超12個贊
最好使用組合user_agent并ip獲得更準確的結果,許多用戶可能具有相同的IP但通常具有不同的用戶代理:
request()->userAgent();
request()->ip();
或者,如果你使用web中間件(不是api),Laravel 會為每個客戶端啟動一個會話。您可以更改會話驅動程序并使用database而不是 default file。
這樣,Laravel 將為每個客戶端存儲一條記錄,sessions其中包含您需要的所有信息,甚至更多信息:
Schema::create('sessions', function ($table) {
$table->string('id')->unique();
$table->unsignedInteger('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('payload');
$table->integer('last_activity');
});
如您所見,ip_address有user_agent和last_activity。這user_id將null適用于來賓用戶,并且對經過身份驗證的用戶具有價值。
請參閱Laravel 文檔來配置您的會話驅動程序以使用database.

TA貢獻1817條經驗 獲得超6個贊
您將如何獲得 IP 地址。
為 ip 地址及其訪問時間戳創建一個新表。
檢查如果 IP 不存在或time()-saved_timestamp > 60*60*24
(1 天),將 IP 的時間戳編輯為 time()(表示現在)并增加您的視圖,否則什么都不做!
此外,您可以通過以下方式獲得 IP$_SERVER['REMOTE_ADDR']
這里提到了更多獲取 IP 的方法。https://stackoverflow.com/a/54325153/2667307
審查了返回的評論127.0.0.1
請試試:-
request()->server('SERVER_ADDR');
或者你可以使用
$_SERVER['SERVER_ADDR'];
或者
$_SERVER['REMOTE_ADDR']
- 4 回答
- 0 關注
- 193 瀏覽
添加回答
舉報