Qiita Conference 2025

徳丸浩 (@ockeghem)

60歳を超えて現役エンジニアであり続けるために心がけていること

6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

概要

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

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

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

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

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

簡潔に書けて良いですね

参考

6
3
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?