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

Duolingo炎上から考える:産業革命時の織工にならないために AIファーストの時代にどう生き残るか

語学学習アプリDuolingoのAIファースト宣言が大炎上。しかしこれは200年前の産業革命時に起きたラッダイト運動と同じ現象では?機械を壊すか使いこなすか。AI時代を生き抜くために必要な「適応力」について、IT企業CEOが現実的な視点で解説します。

icon-loading

AI実装における少子高齢化の絶好機

少子高齢化は本当に日本の弱点なのか?インドネシア出張で目撃した「人材過多の罠」から見えてきた、AI時代における日本の隠れた競争優位性。労働力不足がなぜAI実装を加速させるのか、具体的なデータと現地体験をもとにGruneのCEOが解説します。

icon-loading

AIで脳が退化する?スポーツのように脳も鍛える必要がある理由

AIの普及により人間の脳機能が退化している現代、スポーツが貴族の遊びから必需品になったように、脳トレも必需品となる時代が到来。論理的思考力や記憶力を維持するための新しい習慣について、IT・AI開発会社GruneのCEOが実体験を交えて解説。人狼ゲームや将棋など具体的な脳トレ方法も紹介します。

icon-loading

止まったエスカレーターが教えてくれる、AIと脳の意外な共通点

AI技術と脳科学の意外な共通点を探る。人間の脳もコンピューターも「予測による差分処理」で驚異的なエネルギー効率を実現している。止まったエスカレーターで感じる違和感から自由エネルギー原理まで、最新の脳科学研究とAI開発の現場から見えてきた知能の本質とは?統合失調症や自閉症の新しい理解、動画圧縮技術との類似性など、技術と人間の境界を考察する。

icon-loading

「なんで?」に無限に答えるAIと育つ子どもたち

AIネイティブ世代の登場で教育が激変している。「虹はなんで見えるの?」という子どもの質問に親は3回で降参するが、AIは疲れることなく無限に答え続ける。シンガポールでは小学校でAI教育が始まり、40人の教室が時代遅れに。AIと協働することが基礎能力となる時代に企業はどう準備すべきか。

icon-loading

運転が禁止される日は来るのか?:自家用車の稼働率はわずか5% | 自動運転車が走る都市

自家用車の稼働率はわずか5%—95%の時間は駐車場で眠っている現実をご存知ですか?サンフランシスコで300台が24時間稼働するWaymo無人タクシーの衝撃と、2025年東京実証実験開始のニュース。自動運転技術が描く未来都市では信号が消え、駐車場が公園に変わり、マイカーという概念が消滅する。IT・AI業界のCEOが語る、運転禁止時代の到来。