在 laravel 中正确地为 NULL 变量分配默认值

Assign a default value for NULL variables properly in laravel

我的 laravel 控制器中有以下索引函数

public function index()
    {
        $user = Auth::user();

        if(DepartmentUser::where('user_id', $user->id)->exists()){
            $jobTitleId = DepartmentUser::where('user_id', $user->id)->first()->job_title_id;
            $jobTitle= JobTitle::where('id',$jobTitleId)->first();
            return view('dashboard.supplier.profile.basic-info.index', [
            'user' => $user,
            'jobTitle' => $jobTitle,
        ]);
        }
        else{
            $jobTitle="";
            return view('dashboard.supplier.profile.basic-info.index', [
                'user' => $user,
                'jobTitle' => $jobTitle,
            ]);
        }
    }

有时$jobTitle可以为空,

但是从我的视图文件中,我正在检查这个 $jobTitle 是否可用。

如果此 $jobTitle 为 null 而不是使用

,是否有更好的方法来分配默认值
$jobTitle=""; 

如果你的意思是 re-declare $jobTitle,是的,你可以。这是您代码的重构版本(我也删除了一些未使用的变量)

$departmentUser = DepartmentUser::where('user_id', auth()->id())->first();

// If $departmentUser is Empty, make it null. Else find job title based on id
$jobTitle= !$departmentUser ?: JobTitle::find($departmentUser->job_title_id);

  return view('dashboard.supplier.profile.basic-info.index', [
    'user' => auth()->user(),
    'jobTitle' => $jobTitle
  ]);
}
public function index()
    {
        $user = Auth::user();

        if(DepartmentUser::where('user_id', $user->id)->exists()){
            $jobTitleId = DepartmentUser::where('user_id', $user->id)->first()->job_title_id;
            $jobTitle= JobTitle::where('id',$jobTitleId)->first();
            return view('dashboard.supplier.profile.basic-info.index', [
            'user' => $user,
            'jobTitle' => $jobTitle,
        ]);
        }
        else{            
            return view('dashboard.supplier.profile.basic-info.index', [
                'user' => $user,
                'jobTitle' => $jobTitle ?? null, // or instead of null you can write ""
            ]);
        }
    }