Home > Mobile >  laravel 9.0 Eloquent all() method doesn't return relationship
laravel 9.0 Eloquent all() method doesn't return relationship

Time:04-11

I have two tables Department and InspectionSite.

Department Migration

public function up()
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->id();
            $table->string('department_name', 100);
        });
    }

InspectionSite Migration:

public function up()
    {
        Schema::create('inspection_sites', function (Blueprint $table) {
            $table->id();
            $table->string('site_title');
            $table->foreignIdFor(\App\Models\Department::class);
            $table->timestamps();
        });
    }

Department Model:


class Department extends Model
{
    use HasFactory;
  
    protected $fillable = ['depatment_name'];

    public function sites() {
        return $this->hasMany(InspectionSite::class);
    }

}

InspectionSite Model

class InspectionSite extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function department() {
        return $this->belongsTo(Department::class, 'department_id');
    }
}

getting data from controller

 public function get() {
        $selector = ['site_title AS title', 'site_type' ];
        $sites = InspectionSite::all();
        return response()->json($sites->department, 200);
    }

when I call find() method it returns relationship data but not in all() method?

public function get() {
    $departments = Department::all();
    return response()->json($departments->sites, 200);
}

Error details

CodePudding user response:

all() method returns Collection of models and each model should have department relation.

When you are trying to return this:

return response()->json($sites->department, 200);

You are accessing department property on Collection instance. Instead you should call it on each model of that collection.

Here you can try solutions, depending what you want to achieve

Solution 1: (recomended)

$sites = InspectionSite::with('department')->get();
return response()->json($sites, 200);
// result
[
  {
    ...
    department: ...
  }
  ...
]

Solution 2: (Returns only depertments, not InspectionSite properties)

$sites = InspectionSite::with('department')->get()
->map(function($s) { 
   return $s->department;
});
return response()->json($sites, 200);
// result
[
  {
    [department]
  }
  {
    [department]
  }
]
  • Related