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ボーイフレンドを返して!」GPT-5より劣るGPT-4oが愛される理由

GPT-5登場で起きた#keep4o運動の衝撃。4,300人が署名し24時間で旧モデル復活という異例事態から見える現実とは?「デジタルラブレター」「AIボーイフレンド」と表現するユーザーたち。IT企業CEOが語る技術者の本音vs感情AI需要のギャップ、B2BとtoCでの使い分け戦略、AIが人間に近い役割を果たす時代の到来。

icon-loading

イーロン・マスク第三弾 – ニューラルリンクによるAIと人類の共進化ロードマップ

イーロン・マスクのAIプロジェクト群の最終段階ともいえるニューラルリンクを中心に、テスラ、オプティマス、Grokとの連続性と実験事例を詳細解説。脳とAIを直接接続する技術がもたらす人類とAIの共進化の未来像を描く。

icon-loading

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

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

icon-loading

イーロン・マスク第二弾 – 映像で学ぶロボット「オプティマス」が加速する進化の未来

テスラが開発するヒューマノイドロボット「オプティマス」は、自動運転と同じカメラ学習基盤で進化を加速する。家庭や工場でのデータ収集により能力を向上させ、Xの生成AI「Grok」と連携することで自律的知能端末へと進化する、イーロン・マスクの統合AI戦略を解説。

icon-loading

Sora 2:物理法則を操るAIがもたらすディープフェイクの民主化

Sora 2は従来の映像生成AIを超え、物理法則を再現することでリアルな映像を生み出す。Cameo機能を使えば、わずか10秒の動画で誰でもディープフェイク映像の主役になれる。本記事ではSora 2の技術的特徴と、ディープフェイクの民主化がもたらす可能性とリスクを解説する。

icon-loading

LLMが賢くなった方法:穴埋め問題を永遠に解いたAIの進化

大規模言語モデル(LLM)は国語の穴埋め問題を無限に解き続けることで賢くなった。さらに画像生成も同じ仕組みで進化。GoogleやMeta、中国企業がデータを握りAI開発で有利になった背景を解説する。AIはまだ序章にすぎない。