'I'm working at laravel project but there is always that error : ErrorException Creating default object from empty value

this is my candidatController.php the error is in the line before the last line($prev_canditure->etat="archifé";)

$candidat_nw=Candidat::orderby('created_at','DESC')->first();
$prev_canditure=Candidature::where('candidat_id','=',$candidat->id)->orderby('created_at', 'DESC')->first();

$prev_canditure->etat = "Archivé";
$prev_canditure->save();


Solution 1:[1]

From your code you can use a defensive code approach by checking if the query will return null

$candidat_nw=Candidat::orderby('created_at','DESC')->first();
$prev_canditure=Candidature::where('candidat_id','=',$candidat->id)->orderby('created_at', 'DESC')->first();

if (!(empty($prev_candidature))){
$prev_canditure->etat = "Archivé";
$prev_canditure->save();

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1