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>

And call it like this:

  url="{{ $book->url }}"
  title={{ $book->title }}
  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.

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

  url="{{ $book->url }}"
  title={{ $book->title }}

>Solution :

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

    "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.

Leave a Reply