I have these tables: ERD of my database
I'm making an API and I've built relationships among theses tables:
1.
class address extends Model
{
public $timestamps=false;
protected $guarded=[];
protected $primaryKey = 'addressID';
protected $fillable = ['streetAddress','country','city','postalCode','employeeID'];
public function employee()
{
return $this->belongsTo(employee::class);
}
}
2.
class department extends Model
{
public $timestamps=false;
protected $primaryKey = 'departmentID';
protected $fillable= ['departmentName'];
public function role()
{
return $this->hasMany(role::class);
}
public function employees()
{
return $this->hasMany(employee::class);
}
3.
class employee extends Model
{
public $timestamps=false;
// protected $guarded=[];
protected $primaryKey = 'employeeID';
protected $fillable = ['firstName','lastName','email','password','phone','gender','roleID','departmentID'];
public function address()
{
return $this->hasMany(address::class);
}
public function department()
{
return $this->belongsToMany(department::class);
}
public function role()
{
return $this->belongsToMany(role::class);
}
}
4.
class privilege extends Model
{
public $timestamps=false;
protected $guarded=[];
protected $primaryKey = 'privilegeID';
protected $fillable = ['privilageName','roleID'];
public function statuse()
{
return $this->hasMany(statuse::class);
}
public function role()
{
return $this->belongsTo(role::class);
}
}
5.
class role extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $primaryKey = 'roleID';
protected $fillable = ['roleName','departmentID'];
public function privilege()
{
return $this->hasMany(privilege::class);
}
public function employee()
{
return $this->hasMany(employee::class);
}
public function department()
{
return $this->belongsTo(department::class);
}
}
6.
class statuse extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $primaryKey = 'statusID';
protected $fillable = ['edit', 'delete', 'view','privilegeID'];
public function privilege()
{
return $this->belongsTo(privilege::class);
}
}
Now my role and employee tables are dependent on department table so I want that when I delete any department, it's related employees and roles should also be deleted. I don't know how to do it using eloquent model.
I've tried this in my role Controller but it's not working.
public function destroy($id)
{
$roles = new role;
$roles = $roles::find($id);
$roles->$roles->departments()->attach(['departmentID']))->delete();
//$roles->delete($roles->departments()->attach(['departmentID']));
if ($roles) {
$finaldata['status'] = "Record Deleted";
$finaldata['reason'] = "Record Deleted Successfully";
} else {
$finaldata['status'] = "Record Not Deleted";
$finaldata['reason'] = "Record was not present";
}
$finaldata['deleted role data '] = $roles;
return response()->json($finaldata);
}
}
May be I'm missing any point or logic here, kindly guide me.