forked from eatvio/eatvio-infra
85 lines
2.2 KiB
PHP
85 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Livewire\Recipe;
|
|
|
|
use App\Models\Recipe;
|
|
use App\Models\Tag;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Str;
|
|
use Livewire\Component;
|
|
use Livewire\WithPagination;
|
|
|
|
class ListView extends Component
|
|
{
|
|
use WithPagination;
|
|
|
|
public $search = '';
|
|
|
|
public $typeFilter = 'all';
|
|
|
|
public $tag = '';
|
|
|
|
public $author;
|
|
|
|
protected $queryString = [
|
|
'search' => ['except' => ''],
|
|
'typeFilter' => ['except' => 'all'],
|
|
'tag' => ['except' => ''],
|
|
'author' => ['except' => ''],
|
|
];
|
|
|
|
public function render()
|
|
{
|
|
if ($this->author) {
|
|
$author = $this->author;
|
|
$user = User::find($author);
|
|
$recipes = $user ? $user->author_of_recipe() : [];
|
|
} elseif ($this->tag) {
|
|
$tagId = Str::of($this->tag)->split('/-/')->first();
|
|
$recipes = Tag::find($tagId)->recipes();
|
|
} elseif ($this->search && mb_strlen($this->search) > 2) {
|
|
$recipes = Recipe::where('title', 'rlike', $this->search);
|
|
} else {
|
|
$recipes = (new Recipe());
|
|
}
|
|
|
|
if ($this->typeFilter === 'user') {
|
|
$recipes = $recipes->whereRelation('author', 'is_consultant', false);
|
|
}
|
|
|
|
if ($this->typeFilter === 'consultant') {
|
|
$recipes = $recipes->whereRelation('author', 'is_consultant', true);
|
|
}
|
|
|
|
return view(
|
|
'livewire.recipe.list-view',
|
|
[
|
|
'recipes' => $recipes->orderByDesc('updated_at')->paginate(10),
|
|
'rawTypes' => $this->getTagsCollection(),
|
|
]
|
|
);
|
|
}
|
|
|
|
private function getTagsCollection()
|
|
{
|
|
return Recipe::all()->map(
|
|
fn ($r) => [
|
|
$r->type,
|
|
$r->tags->map(fn ($t) => $t->id.'-'.$t->name)->all(),
|
|
]
|
|
)->reduce(function ($acc, $item) {
|
|
[$type, $tagNames] = $item;
|
|
|
|
foreach ($tagNames as $name) {
|
|
if (isset($acc[$type][$name])) {
|
|
$acc[$type][$name] += 1;
|
|
} else {
|
|
$acc[$type][$name] = 1;
|
|
}
|
|
}
|
|
|
|
return $acc;
|
|
});
|
|
}
|
|
}
|