Home > database >  Assign a default value for NULL variables properly in laravel
Assign a default value for NULL variables properly in laravel

Time:04-25

I have the following index function in my laravel controller

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,
            ]);
        }
    }

There sometimes $jobTitle can be null,

But from my view file I'm checking if this $jobTitle is a available or not.

Is there have better way to assign default value if this $jobTitle is null rather than using

$jobTitle=""; 

CodePudding user response:

If you mean re-declare $jobTitle, yes you can. This is refactor version of your code (also i remove some unused variable)

$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
  ]);
}

CodePudding user response:

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 ""
            ]);
        }
    }
  • Related