Search code examples
phplaravellaravel-8laravel-relations

Get Country list from database and get Attempt to read property "country_name" on null


While trying to create show my students on Laravel 8, I met with some errors, first it wasn't creating the students, then I get errors on /students/ page

Attempt to read property "country_name" on null

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>

Student Model

    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);
    }

}

country model

    class Country extends Model
{
    protected $fillable = ['id', 'phone_code', 'country_code', 'country_name'];
    use HasFactory;
    public function student()
    {
        return $this->hasMany(Student::class);
    }
}

studentController

 public function index(Request $request)
{
    $students = Student::paginate(50);
    $countries = DB::table('countries')->get();
    return view('students.index', compact( 'students','countries'));
}

Solution

  • Since foreignKey not laravel convention so you have to mention foreignKey in belongsTo.I believe foreignKey is country in Student Table

    public function countries()
    {
        return $this->belongsTo(Country::class,'country','id');
    }
    

    And in Country Model

     public function student()
        {
            return $this->hasMany(Student::class,'country','id');
        }
    

    Then you can access

     $students = Student::with('countries')->paginate(50);
    

    BelongsTo method description

    belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)