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

GrokのSpicy Modeと性欲が動かすテクノロジーの歴史 – エロ本自販機からAIアダルトへ

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

icon-loading

「Attention Is All You Need」とは?Transformerが変えたAIの読み方を解説

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

icon-loading

再帰的自己改善するAIがコードを書く時代へ — AGIへの道筋を解説

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

icon-loading

AIでフロントエンド開発を加速する:Claudeを活用してHTML・CSS・Tailwind CSSをより速く作る方法

AIを活用してフロントエンド開発を効率化する実践的な方法を紹介。HTML・CSS・Tailwind CSSの繰り返し作業を減らし、開発スピードを大きく向上させる現場ベースのワークフローを解説します。

icon-loading

AIがある前提の教育をちゃんと考えてみる

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

icon-loading

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

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