I’m working with Laravel 8 to develop my Forum project. So I created a table called answers, and here is the Migration for that:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->text('answer');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('question_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
}
And then in order to make relation between Question Model & Answer Model, I added these:
Question.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
User.php:
public function answers()
{
return $this->hasMany(Answer::class);
}
After that, I added this for showing the question information:
@foreach($show->answers as $ans)
<table class="table table-striped table-bordered table-responsive-lg">
<thead class="thead-light">
<tr>
<th scope="col"></th>
<th scope="col">Answer</th>
</tr>
</thead>
<tbody>
<tr></tr>
<tr>
<td style="text-align:right">
<div><span>Writer: </span><a href="">{{ $ans->id->name }}</a></div>
</td>
<td style="text-align:right">
<p>
{{ $ans->answer }}
</p>
</td>
</tr>
</tbody>
</table>
@endforeach
But now I get this error:
ErrorException Trying to get property ‘name’ of non-object
So what is going wrong here? How can I properly return the name of user who asked a question?
I would really appreciate if you share any idea or suggestion about this,
Thanks.
UPDATE #1:
UPDATE #2:
class Answer extends Model
{
protected $fillable = ['answer', 'user_id', 'question_id'];
}
Advertisement
Answer
you should build the relation between Answer an User models in Answer model:
class Answer extends Model
{
protected $fillable = ['answer', 'user_id', 'question_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function question()
{
return $this->belongsTo(Question::class);
}
}
and in your blade, assuming that the $ans is an instance of Answer model, you can use:
{{ $ans->user->name }}
