Search code examples
laravelcontrollereloquentrelationships

Laravel Eloquent: Set relationships only if related data exists


I have some Eloquent models with relations to each other, but I want these relations to be set only if related data exists.

For example:

  • Department (Model) -> hasMany -> Worker (Model) (Relation should be set only if the department has related workers, otherwise not set)

Is it possible ? I tried this and failed horrably: (in Department Model)

public function worker() {

     $model = new Department();

     if(isset($model->relations)) {
         return $this->hasMany(Worker::class, 'wrk_department_id');
        }
    }

//EDIT:

When department has no workers my output is like:

{
"data": {
    "type": "department",
    "id": "8",
    "attributes": {
        "accessory": [],
        "department": "Marketing",
        "department_id": 8,
        "dept_floor_id": 2,
        "inventory": [],
        "software": [],
        "worker": []
    },
    "links": {
        "self": {
            "href": "http://127.0.0.1:8000/api/v2/department/8"
        }
    }
},
"links": {
    "self": {
        "href": "http://127.0.0.1:8000/api/v2/department/8"
    }
},
"jsonapi": {
    "version": "1.0"
}

}

When department has workers, everthing works as expected:

{
"data": {
"type": "department",
"id": "1",
"attributes": {
  "department": "Entwicklung",
  "department_id": 1,
  "dept_floor_id": 3
},
"links": {
  "self": {
    "href": "http://127.0.0.1:8000/api/v2/department/1"
  }
},
"relationships": {
  "worker": {
    "data": [
      {
        "type": "worker",
        "id": "5"
      },
      {
        "type": "worker",
        "id": "8"
      },
      {
        "type": "worker",
        "id": "11"
      },
      {
        "type": "worker",
        "id": "13"
      }, //and so on

i'm trying to get rid of the empty arrays (eg.: "worker":[]), which appear when their is no related data


Solution

  • In Department model add the relationship.

    public function worker() {
        return $this->hasMany(Worker::class, 'wrk_department_id');
    }
    

    And when you query inside you method in your-controller.

    $builder = Department::with('other-relationships');
    If('your-condition-check') {
         $builder-with('workers');
    }
    $model = $builder->get();
    

    This is the concept. Use appropriate code for your scenario.