1 week ago

How to point the to the value of a foreign key and not the id

Posted 1 week ago by noblemfd

In my Laravel-5.8 projects I have two models: HrLeaveType and HrLeaveRequest


class HrLeaveType extends Model
    protected $table = 'hr_leave_types';

    protected $fillable = [

    public function leaverequest(){
        return $this->hasMany('App\Models\Hr\HrLeaveRequest');

class HrLeaveRequest extends Model

    protected $table = 'hr_leave_requests';

    protected $primaryKey = 'id';

    protected $fillable = [

    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)

id | leave_type_name

1 | Annual Leave

2 | Maternity Leave

3 | Sick Leave

But may not be in this order


      public function leave_request_approve(Request $request, $id)
         $leaverequest               = HrLeaveRequest::find($id);

        if ($leaverequest->leave_type_id == 1)
            $leaverequest->line_manager_comment    = $request->line_manager_comment;
            HrEmployee::where('user_id', $leaverequest->employee_id)->update([
                'on_leave' => 1

Since leave_type_id is a foreign key in HrLeaveRequest, How do I re-write this:

 if ($leaverequest->leave_type_id == 1)

to point to the leave_type_name. That is if leave_type_name is Annual or Annual Leave (it could be in any case) instead of

if ($leaverequest->leave_type_id == 1)

Thank you

Please sign in or create an account to participate in this conversation.