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同士が秘密の暗号で”性格”を受け渡す時代:Anthropicが明かした「サブリミナル学習」

Anthropicの2025年の研究で、AIが数字列だけで「フクロウ好き」という性格を別のAIに伝達した事実が判明した。人間には読めない暗号で好みや悪癖までが感染する「サブリミナル学習」の仕組みと、AI開発の前提を覆すリスク、現時点の対策を解説します。

icon-loading

ヤマハもホンダも消えた街。別世界の中国深圳

40年前の漁村が人口1,700万人の「アジアのシリコンバレー」に変貌した深圳。街を埋め尽くす電動スクーター、財布すら不要なキャッシュレス社会、そしてデータ統治という制度設計の本質。現地で目撃した中国のAI最前線のリアルをレポートします。

icon-loading

ハルシネーションは敵か味方か – 創造性を加速するAIの取扱説明書

AIが事実と異なる情報をもっともらしく生成する「ハルシネーション」は、実は創造性と表裏一体の特性である。temperatureやtop_pによる制御方法、ポストイットの発明に見る人間の「失敗から生まれた創造」との類似性、経営判断での活用法を解説します。

icon-loading

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

画像認識ではすでに2015年にAIが人間を超えている。診断・画像読影など医師の仕事の多くがAIに代替される一方、身体接触を伴う看護師の仕事は代替が難しい。医療分野で起きつつある「経済価値の大逆転」の可能性と、AI時代の価値の再定義を考察します。

icon-loading

運転が禁止される日は来るのか?:自家用車の稼働率はわずか5% | 自動運転車が走る都市

自家用車は95%の時間、駐車場で眠っている。一方サンフランシスコでは300台のWaymo無人タクシーが24時間稼働中。自動運転技術の安全性の仕組み、すべての車が自動運転になった場合の思考実験、そして変化するビジネスモデルの全体像を考察します。

icon-loading

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

日本の労働人口の49%がAIに代替されるという予測は現実味を帯びている。過去の産業革命と違い、今回は新しい職業の創出が追いつかない可能性が高い。社名変更の決断を下した取締役会議の裏側と、エントリーレベル職の消滅に備える生き残り戦略を解説します。