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がマッチングアプリを通じて人間の恋愛から種の繁栄まで操る時代が到来。TinderのVecTecアルゴリズムから完全自律型AIナンパシステムまで、AI vs AIの代理戦争が始まった現状をIT企業CEOが実例を交えて解説します。

icon-loading

議事録AIと固有名詞の戦い:「やましたとしちか」問題

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

icon-loading

LLMの秘密:「次の言葉を予測するだけ」で人間のように振る舞う技術

LLMは「次の言葉を予測するだけ」の仕組み?ChatGPTやClaudeの動作原理を分かりやすく解説。人間の会話との意外な共通点や、トランスフォーマー技術の基本から「考えるとは何か」という哲学的な問いまで、AI技術の本質を深掘りします。非エンジニア向けに専門用語を使わず、身近な例で説明。

icon-loading

24時間365日のAIテレアポに漂うディストピア感

24時間365日稼働するAIテレアポサービスの登場で浮き彫りになった技術の光と影。社会リソースの無駄遣いからAI vs AIの不毛な戦争まで、IT企業CEOが語るAI技術の適切な使い方と未来への警鐘。

icon-loading

SEO対策は無駄に?GAIO/LLMOの対策が必要?ただ最後はどうなるのか

Google AI Overviewによる検索の根本的変化を分析。CTR最大56%減少の実データと、GAIO/LLMO等の新戦略を解説。しかし「AIに選ばれる」ことに本当に意味があるのか?従来のWebマーケティングモデルの限界と今後の展望をAI企業CEOが考察。

icon-loading

AIフレンドリージャパニーズとシンプリファイドイングリッシュ

AI音声入力と議事録自動化の実践から見えた、日本語特有の同音異義語問題とその対策について解説。シンプリファイドイングリッシュを参考にした「AIフレンドリージャパニーズ」の考え方で、機械にも人間にも理解しやすいコミュニケーション手法を提案。AI時代の新しい働き方のヒントが満載。