Calling a service in livewire

What seems to be the problem:
I need to use a service to save a form.

I tried to declare the service in mount but that’s not accepted

 public function mount(String $action, Content $content)
    {

        $this->contentArticleService = new ContentArticleService();

However if I declare it in a function it is fine

public function storeAndMakeLive()
    {
       
        $this->validate($this->rules, $this->messages);

        $this->contentArticleService = new ContentArticleService();
        $this->contentArticleService->storeAndMakeLive($this);

        return redirect()->route('admin.contents.index');
}

Why can’t I declare it in the mount function? I think the error I got was that the type of $this->contentArticleService was not a Int, booloean, string …

Steps to Reproduce:

Are you using the latest version of Livewire:
yes

Do you have any screenshots or code examples:

Public variables in livewire components can only be certain types. They have to be javascript readable in order for livewire to access the data on the front end as well as the back end (as livewire uses javascript).

@shortbrownman

Is what I have written correct then? or is it better do it in a different way.
Would it be better to pass the service as a variable to the component from the controller?

Doing it all in the storeAndMakeLive() method makes sense. If you need to pass around the ContentArticleService, you might be best by keeping track of the $id and refetch it from database as needed. If the ContentArticleService isn’t something you need to keep track of, I wouldn’t bother putting it as a public global, just instantiate as needed.

Thank you for the help. It’s my first app so I am trying to get approval from the pros

1 Like

You don’t need approval from anyone, you’re doing great! You’ll need to keep whittling away at things, asking questions, and continually find what works for you. If you make things work and you understand how they work, you’re well on your way. There’s not really a “correct” way to do things in programming. Just ways to get things done and way people want things to be done.

1 Like

Do everything in the component’s own controller?