thumbnail

Faster way to check Laravel component existence

Rawa Hamid
Rawa Hamid 1 min read
2 months ago August 7, 2024

If you want to check the existence of a component, for whatever reason, you may use livewireComponentsFinder class to achieve it.

To access livewireComponentsFinder methods, do the following:

app(LivewireComponentFinder::class);

Then, we need to access the livewire manifest (the cached livewire components):

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

it returns an array of components, something like:

array:1 [
    'slug-generator' => "App\Http\Livewire\SlugGenerator",
]

All we need, is to search against the given array:

$manifest = app(LivewireComponentsFinder::class)->getManifest();
 
return (bool) array_search(SlugGenerator::class, $manifest); // return boolean

If we want to use it as a global function, we may need to make it works globally,

/**
 * Check if the livewire component exists or not
 *
 * @param object|string $component
 * @return bool
 */
function lw_component_exists(object|string $component): bool {
    $manifest = app(LivewireComponentsFinder::class)->getManifest();
 
    if ($component instanceof Livewire) {
        return (bool) array_search($component, $manifest);
    }
 
    if (is_string($component)) {
        return (bool) array_key_exists($component, $manifest);
    }
 
    return false;
}

We check, if the given component is an object type (class), or a string, based on that, we search for the key or the value.

Update

Since the component manifest will be deleted in the upcoming version of livewire (V3), I found another way to the same trick with another methods, which is the following:

use Livewire\Livewire;
 
function lw_component_exists(string $component): bool {
    try {
        Livewire::getClass($component);
 
        return true;
    } catch(\Throwable $th) {
        return false;
    }
}

It's simply getting the class name, and if it's not existed, it simply throws a ComponentNotFoundException, and you may deal with it however you like.