Search code examples
laravellaravel-livewire

Laravel Livewire error when I add a constructor to call a service class


I've got a piece of code I want to reuse. I've read this Laravel cleaner code article and this other Laravel Services Pattern article, where I have realized I can reuse code in several places of the application by using services classes.

In this case, I created a new MyService class, inside a new folder app/Services/MyService.

namespace App\Services;

class MyService
{
    public function reuse_code($param){
       return void;
    }
}

The problem comes when I want to call the class through the constructor inside a Livewire class component, as follows:

<?php

namespace App\Http\Livewire;

use App\Services\MyService;
use Livewire\Component;
use Livewire\WithPagination;

class LivewireTable extends Component
{
    use WithPagination;

    private $myClassService;

    public function __construct(MyService $myService)
    {
        $this->myClassService = $myService;
    }

    public function render()
    {
       $foo = $this->myClassService->reuse_code($param);
       return view('my.view',compact('foo'));
    }
}

The error displayed is the following:

Argument 1 passed to App\Http\Livewire\LivewireTable::__construct() must be an instance of App\Services\MyService, string given

(However, If I use a trait, there are no problems. But I am afraid then my traits collide as previous experiences)

How do I fix it? What am I missing?


Solution

  • Solved Just like @IGP said, reading in the livewire docs it says:

    In Livewire components, you use mount() instead of a class constructor __construct() like you may be used to.

    So, my working code is as follows:

        <?php
        
        namespace App\Http\Livewire;
        
        use App\Services\MyService;
        use Livewire\Component;
        use Livewire\WithPagination;
        
        class LivewireTable extends Component
        {
            use WithPagination;
        
            private $myClassService;
        
            public function mount(MyService $myService)
            {
                $this->myClassService = $myService;
            }
        
            public function render()
            {
               $foo = $this->myClassService->reuse_code($param);
               return view('my.view',compact('foo'));
            }
        }