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のハルシネーションを正しく理解し、temperature・top_p・プロンプトで出力を制御する実践法を解説。gpt-5の抑制傾向、人間の創造性やSFが技術革新に与えた影響、ポストイットとペニシリンの発明エピソードまで網羅する。

icon-loading

LLMを変えた分岐点:「Attention Is All You Need」とTransformerの前後比較

論文「Attention Is All You Need」が提案したTransformerは、AIの文章理解と生成を根本から変えた。本記事では、その仕組みと前後比較をビジネス視点で解説し、なぜ今この技術を知ることが戦略的メリットになるのかを明らかにする。

icon-loading

イーロン・マスク第一弾 – テスラの自動運転戦略:ウェイモとの決定的な違いとLiDAR不要論

イーロン・マスク率いるテスラの自動運転戦略を解説。ウェイモとのセンサー構成の違い、LiDAR不要論、トップダウン経営による大胆な方針転換、そして完全AI制御への移行までを網羅。長期的にはロボット「オプティマス」との連携を視野に入れたテスラが有利とする理由を探る。

icon-loading

10km先のエロ本からGrokのSpicy Modeへ – 性欲がテクノロジーを進化させる

性欲は人類最強の技術普及ドライバーである。VHS普及からGrokのSpicy Modeまで、アダルトが牽引してきたイノベーションの歴史と、AI時代における性欲とテクノロジーの新たな関係性について、IT企業CEOが実体験を交えて解説。