Search code examples
laravellaravel-livewire

Laravel check livewire component existence


I want to check if a livewire component exists before rendering.
My program has modules and each client has some of those modules enabled. I can get the list of modules a client has with $client->getModules().
Each module can implement livewire components to enhance functions of the program. I want to render those components if they exist in the correct section of the program.
For example in the user creation view, I would have this:

@foreach($client->getModules() as $module)
    if( component_exists( $module . '::users.create' ) )
        @livewire( $module . '::users.create' )
    endif;
@endforeach

If the module implements something related to the user creation, it will have the livewire component users.create, but not all modules will enhance user creation.
I need to assert the existence of the component before rendering it.
I was wondering if there is something like component_exists( Component::class ), otherwise, I would love to see if someone could give me a hint in how to create it as a helper function.


Solution

  • You can take advantage of LivewireComponentsFinder class to check if component is in manifest :

    app(LivewireComponentsFinder::class)->getManifest();
    

    If you want to create a helper, I created laravel-helpers. So, you can create a helper like this:

    function component_exists($class)
    {
        $manifest = app(\Livewire\LivewireComponentsFinder::class)->getManifest();
    
        return (bool) array_search($class, $manifest);
    }