在尝试在 Laravel 8 上创建展示我的学生时,我遇到了一些错误,首先它没有创建学生,然后我在 /students/ 页面上遇到错误
尝试在 null 上读取属性“country_name”
index.blade.php
<tbody id="allocate-table-body">
@foreach($students as $student)
<tr class="id-card">
<td><a target="_blank" href=""> {{$student->id}}</a></td>
<td> {{$student->name}}</td>
<td>{{$student->countries->country_name}}</td>
<td>{{$student->phone}}</td>
<td>{{$student->work}}</td>
<td>{{$student->group}}</td>
<td>{{$student->email}}</td>
<td><a class="btn btn-success" href="#">edit</a></td>
</tr>
@endforeach
</tbody>
学生模型
class Student extends Model
{
use HasFactory;
public $fillable = [
'name',
'marital',
'gender',
'country',
'city',
'education',
'work',
'phone',
'group',
'email',
'description'
];
public function countries()
{
return $this->belongsTo(Country::class);
}
}
国家模式
class Country extends Model
{
protected $fillable = ['id', 'phone_code', 'country_code', 'country_name'];
use HasFactory;
public function student()
{
return $this->hasMany(Student::class);
}
}
学生控制器
public function index(Request $request)
{
$students = Student::paginate(50);
$countries = DB::table('countries')->get();
return view('students.index', compact( 'students','countries'));
}