Reputation: 1333
In my Laravel-5.8 projects I have two models: HrLeaveType and HrLeaveRequest
Model:
class HrLeaveType extends Model
{
protected $table = 'hr_leave_types';
protected $fillable = [
'leave_type_name',
'no_of_days',
'leave_type_code',
];
public function leaverequest(){
return $this->hasMany('App\Models\Hr\HrLeaveRequest');
}
}
class HrLeaveRequest extends Model
{
protected $table = 'hr_leave_requests';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'employee_id',
'department_id',
'leave_type_id',
'reason',
'line_manager_comment',
];
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType','leave_type_id');
}
}
Employee Make several leave requests.
If the Leave Type is Annual or Annual Leave or annual leave the application should follow the condition in the controller below. But the issue is, we cannot say that the leave_type_id for the Annual Leave will be 1.
HrLeave Type have two fields: id (auto-increment) and leave_type_name (varchar)
1 | Annual Leave
2 | Maternity Leave
3 | Sick Leave
But may not be in this order
Controller
public function leave_request_approve(Request $request, $id)
{
$leaverequest = HrLeaveRequest::find($id);
if ($leaverequest->leavetype()->leave_type_name == 'Annual' || $leaverequest->leavetype()->leave_type_name == 'Annual Leave')
{
$leaverequest->line_manager_comment = $request->line_manager_comment;
$leaverequest->save();
HrEmployee::where('user_id', $leaverequest->employee_id)->update([
'on_leave' => 1
]);
}
}
Since the user can't determine if Annual Leave is carrying the leave_type_id as 1, Instead of
if ($leaverequest->leave_type_id == 1)
I used
if ($leaverequest->leavetype()->leave_type_name == 'Annual' || $leaverequest->leavetype()->leave_type_name == 'Annual Leave')
When I submitted, I got this error:
#message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$leave_type_name"
How do I resolve it?
Thank you
Upvotes: 0
Views: 289
Reputation: 496
Try the following:
$leaveType = $leaverequest->leavetype;
if ($leaveType && ($leaveType->leave_type_name == 'Annual' || $leaveType->leave_type_name == 'Annual Leave'))
Side note: It's better to have these strings 'Annual' & 'Annual Leave' as constants or Enums.
Upvotes: 2