In this lesson, let's see how you can call an external class from the Livewire component, like a Service class.
For example, you create a post, then send an email, updating other tables in the DB. So imagine this code has way more lines of code:
use App\Models\Post; class PostForm extends Form{ // ... public function save(): void { Post::create($this->all()); $this->reset('title', 'body'); }}
So we create some PostService
where all the potential code for the post would go there.
app/Services/PostService.php:
class PostService{ public function storePost(string $title, string $body): void { Post::create([ 'title' => $title, 'body' => $body, ]); }}
Then you can use that service in a typical Laravel Controller. You can read about it in posts like Laravel Controller into Service Class with Injection or Service Classes in Laravel: All You Need to Know or check more here.
In Livewire we can call service the same way by creating a new PostService
.
use App\Services\PostService; class PostForm extends Form{ // ... public function save(): void { Post::create($this->all()); (new PostService())->storePost($this->title, $this->body); $this->reset('title', 'body'); }}
Or by adding a service as a parameter in the method.
use App\Services\PostService; class PostForm extends Form{ // ... public function save(): void public function save(PostService $postService): void { (new PostService())->storePost($this->title, $this->body); $postService->storePost($this->title, $this->body); $this->reset('title', 'body'); }}