Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I avoid having to use isset() in Laravel Blade templates?

I’ve got a Blade file like this:

<a href="{{ $url }}" class="{{ $wrapperClass }}">
  <p class="{{ $paraClass }}">{{ $title }}</p>
</a>

And call it like this:

<x-mycomponent
  url="{{ $book->url }}"
  title={{ $book->title }}
  wrapper-class=""
  para-class = ""
/>

Works great, but whenever I want to add a variable to the component, I need to add this to each file where I call this component.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I write it without having to specify all variables and without having to use isset() or {{ $myvar ?? '' }} in Blade? like this:

<x-mycomponent
  url="{{ $book->url }}"
  title={{ $book->title }}
/>

>Solution :

You can assign default values for your properties like the below’s peace of code:

@props([
    "product" => null
])

<a href="#">{{ $product }}</a>

and then, you can call your component in both these ways:

<x-mycomponent />
<x-mycomponent product="$product" />

Note: @props is a Blade directive that allows you to pass data from a parent component to a child component.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading