Q:

Laravel - Trying to get property 'email' of non-object while trying to send notification

In my Laravel-5.8, I want to send email notification to a particular hod:
public function show($id)
{
    if (! Gate::allows('leave_request_review')) {
        return abort(401);
    }

    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;    

    $leaverequest = HrLeaveRequest::findOrFail($id);
    $departmentId               = $leaverequest->department_id;
    $hodId                      = DB::table('hr_departments')->select('dept_head')->where('id', $departmentId)->first()->dept_head;
    $hodEmail                   = DB::table('hr_employees')->select('email')->where('id', $hodId)->where('company_id', $userCompany)->first()->email; 
    die(var_dump($departmentId));

    $hoddetails = [
        'subject' => 'Leave for : '.$employeeFirstName,
        'greeting' => 'Dear '.$hodFirstName . ' '. $hodFirstName . ',',
        'body' =>  'Please note that you have a Leave request awaiting your approval (' . $employeeFirstName . ' ' .$employeeLastName. ') ',
        'line1' => 'Please note that you have a Leave request awaiting your approval (' . $employeeFirstName . ' ' .$employeeFirstName. ') ',
        'thanks' => 'Thank you!',            
        'hod_email' => $hodEmail,
        'hod_id' => $hodId,
        'notification_type' => 'HOD Leave Approval',           
    ];

    Notification::route('mail', $hoddetails['hod_email'])
        ->notify(new \App\Notifications\Leave\LineManagerToHod($hodetails));

    return View::make('hr.employee_leaves.show')
        ->with('leaverequest', $leaverequest);
}

Then I got this error:

Trying to get property 'email' of non-object

When I 
dd($hodId);

in
$hodId = DB::table('hr_departments')->select('dept_head')->where('id', $departmentId)->first()->dept_head;

I found that dept_name is null and that makes $hodEmail to be null so this triggers the error.
How do I resolve this? Or even terminate the the action or show a message instead of the error?

A:

You can simply check for $hodEmail exists operation like
$hodEmail = DB::table('hr_employees')->select('email')->where('id', $hodId)->where('company_id', $userCompany)->first();
if($hodEmail){
      $hodEmail=$hodEmail->email;
}else{
      $hodEmail="somedefault@email.com";

}

Also you can simple use cascading like
$hodEmail = DB::table('hr_employees')->select('email')->where('id', $hodId)->where('company_id', $userCompany)->first()->email??"somedefault@email.com";

