⌘K
Noting Found

View all related articles

Faster way to check Laravel component existence

Snippets 1 min read

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:

1app(LivewireComponentFinder::class);

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

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

it returns an array of components, something like:

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

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

1$manifest = app(LivewireComponentsFinder::class)->getManifest();
2 
3return (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,

1/**
2 * Check if the livewire component exists or not
3 *
4 * @param object|string $component
5 * @return bool
6 */
7function lw_component_exists(object|string $component): bool {
8 $manifest = app(LivewireComponentsFinder::class)->getManifest();
9 
10 if ($component instanceof Livewire) {
11 return (bool) array_search($component, $manifest);
12 }
13 
14 if (is_string($component)) {
15 return (bool) array_key_exists($component, $manifest);
16 }
17 
18 return false;
19}

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:

1use Livewire\Livewire;
2 
3function lw_component_exists(string $component): bool {
4 try {
5 Livewire::getClass($component);
6 
7 return true;
8 } catch(\Throwable $th) {
9 return false;
10 }
11}

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.

That's all ;)

Related Tags

About the Author

Oussama's Profile Picture
Oussama
Full Stack Web Developer | Technical Writer

Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

Comments

Join our newsletter

Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

We care about the protection of your data. Read our Privacy Policy.