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の学習モードが普及すると、知識を「教える」役割は急速にAIへ移る。教師の仕事を分解し、小中高大で「教育」と「預かり」の比率がどう変わるかを整理したうえで、大学は実験インフラと能力認定へ収束する未来を描く。さらに、教育予算を三分の一以下に圧縮しつつ、個別最適化で水準を引き上げられるというAI前提の国家教育改革を提案する。

icon-loading

AIでDjangoのユニットテストを攻略:無理なく運用できるワークフロー構築までの物語

AIを「テストを書く相棒」として活用し、Djangoのユニットテストを無理なく運用できるワークフローを実体験ベースで解説。失敗から学んだプロンプト設計と、現場で本当に使えるAI活用法を紹介します。

icon-loading

人型ロボットである必要は本当にあるのか

AI人型ロボットは本当に必要なのか。非効率とされる人型が選ばれる理由を、学習データ、重機や都市インフラ、社会設計の視点から解説。なぜ世界は人間向けなのかが見えてくる。

icon-loading

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

40年前は漁村だった深圳が、テック大企業と電動スクーター、完全キャッシュレス社会によって「アジアのシリコンバレー」と呼ばれる都市に成長した背景と、中国がAI時代の最前線にいる理由を現地体験から考察する記事。

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の共進化の未来像を描く。