Files
eatvio-infra/app/Livewire/BlogPost/Edit.php
2023-10-04 17:57:09 +03:00

108 lines
2.5 KiB
PHP

<?php
namespace App\Livewire\BlogPost;
use Livewire\Component;
use App\Models\Tag;
use Illuminate\Support\Facades\Auth;
use Livewire\WithFileUploads;
use App\Models\BlogPost;
class Edit extends Component
{
use WithFileUploads;
public BlogPost $blogPost;
public $image = null;
public $state = "archived";
public $title = "";
public $description = "";
public $tags = [];
public $videoUrl = "";
protected $listeners = ['blogPostTagAdded', 'blogPostTagRemoved'];
public function mount(BlogPost $blogPost)
{
$this->name = $blogPost->name;
$this->image = $blogPost->image;
$this->state = $blogPost->state;
$this->title = $blogPost->title;
$this->description = $blogPost->description;
$this->tags = $blogPost->tags;
$this->videoUrl = $blogPost->youtube_url;
}
protected function rules()
{
$rules = [
/* 'image' => 'required|image|max:2048', */
'state' => 'required|in:active,archived',
'description' => 'required|min:3',
'videoUrl' => 'nullable|url|max:2048'
];
return $rules;
}
public function parentComponentTagAdded(Tag $tag)
{
$tagIndex = $tag->id;
$this->tags[$tagIndex] = $tag;
}
public function parentComponentTagRemoved($tag)
{
$tagToDetach = Tag::where('name', $tag)->first();
$this->tags = collect($this->tags)
->filter(fn($curTag) => $curTag['name'] != $tag)
->all();
$this->blogPost->tags()->detach($tagToDetach->id);
}
public function draft()
{
$this->state = 'archived';
$this->publish();
}
public function preview()
{
$this->state = 'archived';
$this->publish();
}
public function publish()
{
$this->validate();
$post = $this->blogPost;
/* $post->image = $this->image->store('blog_posts', 'public'); */
$post->state = $this->state;
$post->title = $this->title;
$post->description = $this->description;
$post->youtube_url = $this->videoUrl;
$post->save();
$tagsIds = collect($this->tags)
->map(fn($curTag) => $curTag['id']);
$post
->tags()
->attach($tagsIds);
$user = Auth::user();
$user->author_of_blog_post()->attach($post->id);
return redirect()->route('blog_post.show', $post->id);
}
public function render()
{
return view('livewire.blog-post.edit');
}
}