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
- What is the most reliable way to fix this bug?
- How can I make the
$comment
variable optional?
2
Answers
I have replaced
<input type="hidden" name="parent_id" value="{{ $comment->id }}">
with:It works: the error is gone. The only question I am left with is:
Should I use
@isset($comment->id)
or@isset($comment)
?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