2021/12/15

3 Essential Checks in Laravel

Contents
  1. Null Check
  2. Empty Check
  3. Zero Check

Do you find your code runs well the first, second, third time, but fails in production? Sometimes the unique but chances are assumed the data would be of “x” kind and actually it was “yyyxz” kind.

Null check

We’ve all made this mistake. Never assume a value won’t be null! 

function getPikachusTrainer() {
    $pokemon = Pokemon::where(“name”, “Pikachu”)->first();
    return $pokemon->trainer->name;
}

Will return an error: 

Trying to get property of non-object

But a simple check:

If ($pokemon) {
    $trainer = Trainer::where(“name”, $pokemon->name);
} else {
    return “sorry, no trainer found”;
}

Will allow us to avoid the issue.

Empty Check

The above works because it is an object and laravel returns null if a query can’t find anything. For arrays, we should not assume the array contains more than 0 elements. 

foreach ($bagOfPokeballs as $key => $pokeball) {
    print($key . “contains the following Pokemon” . $pokeball->name);
}

The above code will cause a similar error: “Trying to get property “name” of non-object”

In that case we can just add !empty($array) to our null check:

If (!empty($bagOfPokeballs) && $bagOfPokeballs) {
    foreach ($bagOfPokeballs as $key => $pokeball) {
        print($key . “contains the following Pokemon” )
        print($pokeball->name)
    }
}

Zero Check

Just like arrays, we should not assume integers are > 0. Especially since Laravel/PHP will return an error when divided by zero.

    Divide By Zero Error

Thankfully, the way to avoid this is easy as pi!

if ($numBattles && $numBattles > 0) {
    $percentageVictories = (($numWins / $numBattles) * 100)
}

関連記事


icon-loading

看護師さんの給料が医師の給料を超えるのはいつか?

AI時代の医療現場で起きている価値の大逆転。医師の診断業務の多くがAIに代替される一方、看護師の物理的なケアの価値が急上昇している現実を、最新データと事例で解説。「看護師の給料が医師を超える日」という挑発的な問いから、医療の本質を考える。

icon-loading

Duolingo炎上から考える:産業革命時の織工にならないために AIファーストの時代にどう生き残るか

語学学習アプリDuolingoのAIファースト宣言が大炎上。しかしこれは200年前の産業革命時に起きたラッダイト運動と同じ現象では?機械を壊すか使いこなすか。AI時代を生き抜くために必要な「適応力」について、IT企業CEOが現実的な視点で解説します。

icon-loading

AI同士が秘密の暗号で”性格”を受け渡す時代:Anthropicが明かした「サブリミナル学習」

Anthropicが2025年に発見した「サブリミナル学習」とは?AI同士が数字やコードを通じて性格や偏見を秘密裏に受け渡す驚異的な現象を解説。フクロウ好きが数字だけで伝染する実例から、AI開発の常識を覆す研究の全貌まで、Grune CEOが技術者向けに分かりやすく紹介。

icon-loading

AI実装における少子高齢化の絶好機

少子高齢化は本当に日本の弱点なのか?インドネシア出張で目撃した「人材過多の罠」から見えてきた、AI時代における日本の隠れた競争優位性。労働力不足がなぜAI実装を加速させるのか、具体的なデータと現地体験をもとにGruneのCEOが解説します。

icon-loading

AIはインフラになる

AIがインフラとなる時代において、採用面接でもAI活用能力が問われるようになった。電気やインターネットと同様、AIを使えない人は生産性で圧倒的な差をつけられる。GruneのCEOが語る、AIインフラ化の現実と実践的なアドバイス。

icon-loading

「AIはツールだから心配ない」と言う経営陣は頭の中がお花畑か嘘を言っている

「AIはツールだから心配ない」と言う経営陣への警鐘。日本の労働人口49%が代替される現実、Grune AI Technologiesへの社名変更決断、プログラマーの生き残り戦略まで。産業革命とは根本的に違う今回のAI革命の本質を解説。