forked from eatvio/eatvio-infra
86 lines
2.1 KiB
PHP
86 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\Casts\AsCollection;
|
|
use CyrildeWit\EloquentViewable\InteractsWithViews;
|
|
use CyrildeWit\EloquentViewable\Contracts\Viewable;
|
|
|
|
class Recipe extends Model implements Viewable
|
|
{
|
|
use HasFactory, InteractsWithViews;
|
|
|
|
protected $casts = [
|
|
'steps' => AsCollection::class,
|
|
'ingredients' => AsCollection::class,
|
|
];
|
|
|
|
protected $withCount = [
|
|
'likes',
|
|
'comments'
|
|
];
|
|
|
|
public function tags()
|
|
{
|
|
return $this->morphToMany(Tag::class, 'taggable');
|
|
}
|
|
|
|
/* public function author() */
|
|
/* { */
|
|
/* return $this->belongsToMany(User::class, 'recipe_author', 'recipe_id', 'user_id'); */
|
|
/* } */
|
|
|
|
public function author()
|
|
{
|
|
return $this
|
|
->hasOneThrough(User::class, RecipeAuthor::class, 'recipe_id', 'id', 'id', 'user_id')
|
|
->withDefault(
|
|
[
|
|
'name' => 'Guest Author',
|
|
'id' => 0,
|
|
'profile_photo_url' => 'https://dev2.eatvio.com/storage/profile-photos/mW87tqy9P8O31Dauyvg8f7GowMNMsgt9J6u47T7S.jpg'
|
|
]
|
|
);
|
|
}
|
|
|
|
public function comments()
|
|
{
|
|
return $this->hasMany(RecipeComment::class);
|
|
}
|
|
|
|
public function likes(): HasMany
|
|
{
|
|
return $this->hasMany(RecipeLike::class);
|
|
}
|
|
|
|
public function isLiked(): bool
|
|
{
|
|
$curUser = auth()->user();
|
|
if ($curUser) {
|
|
return $curUser->recipe_likes()->forRecipe($this)->count();
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public function removeLike(): bool
|
|
{
|
|
$curUser = auth()->user();
|
|
if ($curUser) {
|
|
return $curUser->recipe_likes()->forRecipe($this)->delete();
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public function scopeContainsTag($query, $tagString): Builder
|
|
{
|
|
$tagId = Str::of($tagString)->split('/-/')->first();
|
|
return Tag::find($tagId)->recipes();
|
|
}
|
|
|
|
}
|