File: /home/imensosw/www/mpl.imenso.co/app/Models/Comment.php
<?php
namespace App\Models;
use App\Events\EventCommentedOn;
use App\Events\UserCommentOnPost;
use App\Events\UserDeletedCommentOnPost;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
class Comment extends Model
{
use SoftDeletes;
public function User()
{
return $this->belongsTo(\App\Models\User::class, 'user_id');
}
public function post()
{
return $this->belongsTo(\App\Models\News::class, 'commentable_id');
}
public function tour()
{
return $this->belongsTo(\App\Models\Tour::class, 'commentable_id');
}
public function event()
{
return $this->belongsTo(\App\Models\Event::class, 'commentable_id');
}
public function likes()
{
return $this->morphMany(\App\Models\Like::class, 'likeable');
}
public function reports()
{
return $this->morphMany(\App\Models\Report::class, 'reportable');
}
public function isLikedByUser(User $user)
{
if ($this->likes()->where('user_id', $user->id)->count() > 0) {
return true;
}
return false;
}
public function isLikedByCurrentUser()
{
if (Auth::check()) {
return $this->isLikedByUser(Auth::user());
}
return false;
}
public function isReportedByUser(User $user)
{
if ($this->reports()->where('user_id', $user->id)->count() > 0) {
return true;
}
return false;
}
public function isReportedByCurrentUser()
{
if (Auth::check()) {
return $this->isReportedByUser(Auth::user());
}
return false;
}
public static function addNew($data)
{
$new_comment = new self;
$new_comment->user_id = $data['user']->id;
$new_comment->content = $data['content'];
$new_comment->commentable_id = $data['commentable_id'];
$new_comment->commentable_type = $data['commentable_type'];
$new_comment->save();
if ($data['user']->isFan() && $data['commentable_type'] == \App\Models\News::class) {
event(new UserCommentOnPost($new_comment));
}
if ($data['commentable_type'] == \App\Models\Event::class) {
event(new EventCommentedOn($new_comment->event, $new_comment));
}
return $new_comment;
}
public function resetReportCount()
{
foreach ($this->reports as $report) {
$report->remove();
}
$this->report_count = 0;
$this->save();
}
public function remove()
{
if (Auth::check()) {
if (Auth::user()->id == $this->user->id || Auth::user()->type_id == 5) {
foreach ($this->likes as $like) {
$like->remove();
}
foreach ($this->reports as $report) {
$report->remove();
}
if ($this->user->isFan()) {
if ($this->commentable_type == \App\Models\News::class) {
event(new UserDeletedCommentOnPost($this));
}
}
$this->delete();
return true;
} else {
return false;
}
}
}
}