2

I'm new to laravel and I'm want to check if the value exist and it is equal to 1. Below is what I have tried. But it doesn't work.

if(isset($request['active_year'] == "1")) {
    $activeYear = 1;
    $currentActiveYear = AcademicYear::where('active_year', 1)->update(['active_year' => 0]);
  } else {
    $activeYear = 0;
  }

3 Answers3

1

Try this and let me know.

if(($request['active_year'] == "1") && isset($request['active_year'])) {
    $activeYear = 1;
    $currentActiveYear = AcademicYear::where('active_year', 1)->update(['active_year' => 0]);
  }
  $activeYear = 0;
livreson ltc
  • 733
  • 8
  • 22
1

You don't need else part define it before condition and check with isset

$activeYear = 0;
if(isset($request['active_year']) && $request['active_year'] == '1'){
    $activeYear = 1;
    $currentActiveYear = AcademicYear::where('active_year', 1)->update(['active_year' => 0]);
}
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
0

Firstly, according to the documentation, isset() expects a variable. It can't evaluate expressions, as you are trying with isset($request['active_year'] == "1"). Secondly, this is more related to PHP itself than Laravel.

You should split the checking into two parts: first, check if the variable $request['active_year'] exists. You can do that using isset($request['active_year']) or with !!$request['active_year'](using double-not operator). Then, check whether the value is equal to 1 with $request['active_year'] == "1". Note that using == is a loose comparison. If you wish to also check if the variable is of type string, you should use === which is a strict comparison.

Considering the above, I would write:

if(!!$request['active_year'] && $request['active_year'] === "1") {
    $activeYear = 1;
    $currentActiveYear = AcademicYear::where('active_year', 1)->update(['active_year' => 0]);
} else {
    $activeYear = 0;
}
Andre Ravazzi
  • 611
  • 7
  • 10