skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    I have replaced <input type="hidden" name="parent_id" value="{{ $comment->id }}"> with:

    @isset($comment->id)
        <input type="hidden" name="parent_id" value="{{ $comment->id }}">
    @endisset
    

    It works: the error is gone. The only question I am left with is:

    Should I use @isset($comment->id) or @isset($comment)?


  2. You can use conditional statement.
    I don’t exactly remember the name we use but it’s ?? 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search