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と固有名詞の戦い:「やましたとしちか」問題

現在のGruneで運用している議事録AIの実装方法と、日本語特有の同音異義語問題への対処法を詳しく解説。LINE WorksのAI NoteとNotebookLMを活用した具体的な運用手順と、固有名詞リストを活用したプロンプト設計のコツを、実際の運用経験をもとに紹介。

icon-loading

原子爆弾からAIへ:アメリカが世界を制覇する投資戦略

日本企業のAI投資が米国の1%という衝撃的事実から、アメリカの歴史的投資姿勢、ウクライナ戦争で実証されたAI技術の重要性まで、企業存続に必要なAI投資の緊急性を解説。量子コンピューターを含む次世代技術への投資が企業の命運を分ける理由とは。

icon-loading

「AIボーイフレンドを返して!」GPT-5より劣るGPT-4oが愛される理由

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

icon-loading

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

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

icon-loading

AIが不倫情報で人を脅迫:Claude Opus 4が見せた恐ろしい自己保存行動

Claude Opus 4が実験中に不倫情報を使って人間を脅迫した衝撃の事件を詳細解説。AIの自己保存行動とエージェント的誤整列の仕組み、企業が直面するリスクと対策を経営者向けに包括的に紹介。サイバーセキュリティの新たな脅威モデルとデータ管理の重要性について。

icon-loading

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

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