rawnato's avatar

View Component Exists

Hello my friends,

I'm making some form components in my application to make my page views cleaner!

I'm making an input component like this on my view login.blade.php

<x-layout.auth heading="Sign in" subheading="Fill your data">
     <x-form :action="route('login')">
         <x-form.input type="email" name="email" label="Email" />
         <x-form.input type="password" name="password" label="Password" />
         <x-form.button label="Sign In" />
     </x-form>
</x-layout.auth>

What I want to do in my component and I don't know how to test it is in the example below!

@props(['label'])
<div>
    <x-form.helpers.label :text="$label" />
    @if (???) <- How to check  this "form.input.{{ $attributes['type'] }}" exists
        <x-dynamic-component component="form.input.{{ $attributes['type'] }}" />
    @else
        <input {{ $attributes->merge(['class' => 'border w-full']) }} />
     @endif
    <x-form.errors :messages="$errors->get($attributes['name'])" />
</div>

Thanks for your support! āœŒšŸ»

0 likes
3 replies
LaryAI's avatar
Level 58

To check if a Blade component exists before rendering it, you can use the Blade::exists method provided by Laravel. This method allows you to check if a Blade view file exists for a given component. Here's how you can modify your component to perform this check:

@props(['label'])

<div>
    <x-form.helpers.label :text="$label" />
    @php
        $componentName = "form.input." . $attributes['type'];
    @endphp
    @if (\Illuminate\Support\Facades\Blade::exists($componentName))
        <x-dynamic-component :component="$componentName" :attributes="$attributes->except('type')" />
    @else
        <input {{ $attributes->merge(['class' => 'border w-full']) }} />
    @endif
    <x-form.errors :messages="$errors->get($attributes['name'])" />
</div>

In this solution, we're using the Blade::exists method to check if the component exists. We construct the component name using the type attribute and then pass it to Blade::exists. If the component exists, we render it using the <x-dynamic-component> tag, otherwise, we fall back to a standard <input> tag.

Please note that you need to import the Blade facade at the top of your Blade file if it's not already imported:

@php
use Illuminate\Support\Facades\Blade;
@endphp

Alternatively, you can use the fully qualified namespace when calling the exists method as shown in the example above.

Remember to replace form.input. with the correct namespace or prefix you are using for your form input components.

rawnato's avatar

@LaryAI I got this error Call to undefined method Illuminate\View\Compilers\BladeCompiler::exists()

Ronan-Lenor's avatar

You can use \Illuminate\Support\Facades\View::exists('my-vendor::components.path.to.file') the word components in the path name, may have an impact.

1 like

Please or to participate in this conversation.