0

I have made a blogging application in Laravel 8.

The (single) article view displays a comments form and I am now working on adding a comments reply functionality.

I have moved the code for the comments form in comment-form.blade.php so that I can use both under the article and under every comment.

The form looks like so:

<form method="post" action="{{ route('comment.submit') }}" autocomplete="off">
@csrf
  <fieldset>

      <input type="hidden" name="article_id" value="{{ $article->id }}">
      <input type="hidden" name="parent_id" value="{{ $comment->id }}">

      <div class="form-field">
          <input type="text" name="name" id="name" class="h-full-width h-remove-bottom" value="{{ Auth::user()->first_name }} {{ Auth::user()->last_name }}">
      </div>

      <div class="message form-field">
          <textarea name="msg" id="message" class="h-full-width" placeholder="Your Message"></textarea>

          @error('msg')
          <p class="help-block text-danger">{{ $message }}</p>
          @enderror
      </div>
      <br>
      <input name="submit" id="submit" class="btn btn--primary btn-wide btn--large h-full-width" value="Add Comment" type="submit">
  </fieldset>
</form>

The problem

For the form that is not under a comment (because it is not intended for adding a reply), the line <input type="hidden" name="parent_id" value="{{ $comment->id }}"> throws the below error, because there is no $comment->id:

Undefined variable: comment

Using this fails:

<input type="hidden" name="parent_id" value="{{ $comment->id or 'default' }}">

Questions

  1. What is the most reliable way to fix this bug?
  2. How can I make the $comment variable optional?
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252

1 Answers1

1

You can use the null coalescing operator (??). So what you'll do is {{ $comment->id ?? '' }}

What this does is basically if there's no $comment variable than it'll show the empty string

kopz
  • 738
  • 11
  • 20
Hesan Naveed
  • 199
  • 5