10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PR: フリーランスコネクト株式会社
フリーランスコネクト採用ページ

More than 1 year has passed since last update.

php8のlaravelでもoptional()を使っていませんか

10
Last updated at Posted at 2023-12-07

概要

laravelライフで、バージョン8までよくお世話になっていたへルパのoptional()

optionalで囲った変数から動的メソッドなどを記述した際、
変数がnullの場合にエラーを起こさずにnullを返却してくれるというものです。(参考に記載)

しかし、php8からヌルセーフ演算子というものが追加されました。
挙動としてはoptionalと同じで、同じ効果かつ短く記述できます。
比較するとこんな感じです。

//optionalへルパ
optional(optional($user)->getAddress())->getCity();

//ヌルセーフ演算子
$user?->getAddress()?->getCity();

簡潔に書けて良いですね

参考

10
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?