Files
animethemes-server/app/Concerns/Models/InteractsWithLikes.php
T

40 lines
962 B
PHP

<?php
declare(strict_types=1);
namespace App\Concerns\Models;
use App\Models\User\Like;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Auth;
trait InteractsWithLikes
{
public function like(): Like
{
return Like::query()
->create([
Like::ATTRIBUTE_USER => Auth::id(),
Like::ATTRIBUTE_LIKEABLE_TYPE => Relation::getMorphAlias($this->getMorphClass()),
Like::ATTRIBUTE_LIKEABLE_ID => $this->getKey(),
]);
}
public function unlike(): mixed
{
return Like::query()
->whereBelongsTo(Auth::user())
->whereMorphedTo(Like::RELATION_LIKEABLE, $this)
->delete();
}
/**
* @return MorphMany
*/
public function likes(): MorphMany
{
return $this->morphMany(Like::class, Like::RELATION_LIKEABLE);
}
}