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

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

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

icon-loading

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

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

icon-loading

6年間で小学生AIが博士号AIへと成長、その一方で「寄り添う大学生AI」が恋しい人類

AIはわずか6年で小学生レベルから博士号レベルへと進化した。スケール則に裏付けられた指数的成長は、2030年前後にノーベル賞級の発見をもたらし、自己改善による加速時代を迎える可能性がある。一般ユーザーに寄り添う大学生AIと、ビジネスを変革する博士号AIの違いを解説する

icon-loading

データは新たな石油、でも精製しないとただのドロドロ?

AI時代の「データは新たな石油」というフレーズの本当の意味を解説。石油大国の投資事例やイリヤ・サツケヴァーの発言、データ精製・合成の重要性まで、AIを使いこなすための実践的視点を紹介します

icon-loading

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

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

icon-loading

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

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