Vote model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vote extends Model
{
protected $fillable = [
'type',
'post_id'
];
public function post()
{
return $this->belongsTo('App\Post');
}
}
Vote migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVotesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('votes', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->integer('post_id')->unsigned();
$table->string('ip');
$table->timestamps();
});
Schema::table('votes', function(Blueprint $table) {
$table->foreign('post_id')->references('id')->on('posts');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('votes');
}
}
Post model:
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'url',
'source'
];
public function votes()
{
return $this->hasMany('App\Vote');
}
public function upVotes()
{
return $this->votes()->where('type', 'up')->count();
}
public function downVotes()
{
return $this->votes()->where('type', 'down')->count();
}
public function voteCount()
{
return $this->upVotes() - $this->downVotes();
}
public function recentUserVote()
{
$formatted_date = Carbon::now()->subDays(10)->toDateTimeString();
return $this->votes()->where('ip', getUserIp())->where('created_at', '>=', $formatted_date)->first();
}
}
Post migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('url');
$table->string('source');
$table->string('ip');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
getUserIp() is a function I wrote to get around Cloudflare's proxy, it passes the user's IP as a header, the function checks for the existence of that header, and returns the value if it exists, or if not, returns the user's IP in the normal fashion.