Home > front end >  Eloquent Relationship belongsTo Return Error In Laravel 8
Eloquent Relationship belongsTo Return Error In Laravel 8

Time:06-15

Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.

Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?

My Implementation My District Model

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
    protected $guarded = [];
    public function empdistrict(){
        return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
    }
}

My EmpData Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
    $data= EmpData::all();
    return view('frontend.allusermindata',compact(['data']));
}

My Blade file where I show the data

foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}

But I get this error

Trying to get property 'name' of non-object

CodePudding user response:

foreach($data as $user){
  <p>Name : {{ $user->empName }}</p>
  <p>District : {{ $user->empdistrict->name}}</p>
}

Calling the method returns a BelonsTo class instance. Use laravel magic method by calling it as an attribute.

Further on this question, you'll have performance issues down the line, better load the data in the same query.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
    $data= EmpData::with('empdistrict')->get();
    return view('frontend.allusermindata', compact(['data']));
}
  • Related