Courses

Livewire 3 From Scratch: Practical Course

External Service Class in Livewire

Summary of this lesson:
- Using a Service for business logic
- Implementing dependency injection pattern
- Moving complex logic to service classes
- Maintaining clean component code

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');
}
}
Previous: Quick Tip: Customizing Default Stubs
avatar

Can I call it like:

'app(PostService::class)->storePost($this->title, $this->body);` ?

What's the difference?

avatar

Yes you can. No difference, just different syntax, both work.

avatar
You can use Markdown
avatar
You can use Markdown