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

OpenAIが“gpt-oss”を無料公開──なぜ今、企業が「自社専用のGPT」を持つメリット

OpenAIが無料公開した「gpt-oss」の登場で、企業が自社専用AIを持つ時代が始まりました。中国AI勢への対抗策として投入されたこのオープンウェイトモデルの特徴、ファインチューニングによる自社カスタマイズ方法、導入メリットと注意点を分かりやすく解説します。

icon-loading

自己改善するAIがコードを書く時代へ:汎用人工知能への最短ルート

AIが自らコードを改善し続ける「自己改善型エージェント」が登場。OpenAIのサム・アルトマンがAGIの近道と語るこの技術が、開発業界と人類の未来をどう変えるのかを探る。

icon-loading

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

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

icon-loading

AIの学習は「パクリ」なのか?著作権の判例は?

AI時代の著作権問題について、最新の米国判例を踏まえて解説。Anthropic、Meta社の訴訟でAI学習が「フェアユース」と認められた背景から、人間とAIの学習プロセスの共通性、ビジネスにおけるクリエイティビティの未来まで、経営者・意思決定者が知るべき重要な論点を網羅的に分析します。

icon-loading

AIロボットが動画を見て進化する時代:AIも人間も学び方が変わらなくなってきた

テスラのオプティマスが動画学習で家事を習得し、ジョンズ・ホプキンス大学では手術ロボットが映像から医療技術を学ぶ時代に。従来の条件分岐プログラミングから「見て覚える」AI学習への革命的転換が、製造業・医療・サービス業に与える衝撃と、労働力不足解決への道筋を、AIコンサル企業CEOの視点で解説。