Laravel 有效点击浏览统计功能并记录IP
在laravel 开发中需要统计有效的浏览量展示在表现层,首先逻辑上一个IP只能有一个有效的浏览数量,这是一个一对多的关系用到laravel 函数hasMany()功能。
1.首先在linux中需要用到数据迁移命令 php artisan make:migration create_eyes_table
创建浏览数据表
代码如下:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEyesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('eyes', function (Blueprint $table) {
$table->increments('id');
$table->string('ip')->default("");
$table->integer('article_id')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('eyes');
}
}
2.命令:php artisan migrate
来完成数据表的创建
3.命令:php artisan make:model Eyes
创建浏览数据模型Eyes.php
代码如下:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Eyes extends Model
{
protected $table='eyes';
}
4.在文章模型Article中创建浏览关联
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = 'article';
//获取文章的所有浏览数
public function eyes(){
return $this->hasMany('App\Eyes')->orderBy('created_at','desc');
}
}
5.在文章控制器中ArticleController.php
中构建逻辑关系
<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
//使用类
use App\Http\Controllers\Controller;
use App\Article;
use App\Eye;//引入浏览模型 关系
//前台分类控制器
class ArticleController extends Controller
{
//文章页面展示
public function index($id){
//获取文章信息与赞模型关联的数据
$data=Article::where("id",$id)->withCount('eyes')->first();
$data->user_ip = $this->getIp();//获取用户ip
$param=[
'ip'=>$data->user_ip,
'article_id'=>$id,
'created_at'=>date('Y-m-d h:i:s'),
'updated_at'=>date('Y-m-d h:i:s'),
];
$noArrEye=\DB::table("eyes")->where([['ip','=',$data->user_ip],['article_id','=',$id],])->first();
if(!$noArrEye){
\DB::table("eyes")->insert($param);
}
return view("home.show")->with("data",$data);
}
//获取文章所有查看数
public function eyes(){
return $this->hasMany(\App\Eyes::class);
}
//获取访客ip
public function getIp()
{
$ip=false;
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
for ($i = 0; $i < count($ips); $i++) {
if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
$ip = $ips[$i];
break;
}
}
}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
}
6.文章前台页面代码show.blade.php
代码如下:
浏览量:{{$data->eyes_count}}
OK到这里就完成了