Your question is a good one and it's great that you're using this as a learning opportunity. The errors you're seeing are related to the concept of null safety. In PHP, an object variable can hold either an object or null. If you try to call a method or access a property on a null, you'll get a fatal error.
The static analysis tool phpstan/larastan is warning you about these potential issues. It's telling you that there are places in your code where you're assuming an object will always exist, but there's a chance it could be null.
To avoid these issues, you can use a few strategies:
-
Null coalescing operator (
??): This operator is used to check if a variable is set and not null. If it is, it returns the first operand, otherwise it returns the second operand.
$model = $model ?? new Model();
-
Optional helper: Laravel provides an
optional()helper function that allows you to access properties or call methods on an object. If the object is null,optional()will return a new instance of theOptionalclass, and no methods or properties will be called.
$id = optional($model)->id;
-
Null safe operator (
?->): PHP 8 introduced the null safe operator. If the object is null, null is returned. If it's not, the method or property is called.
$id = $model?->id;
- Check before use: As you mentioned, you can always check if an object is null before using it. This can be a bit verbose, but it's a surefire way to avoid null errors.
if ($model !== null) {
$id = $model->id;
}
Remember, the goal is to ensure that you're not trying to access methods or properties on a null object. How you achieve that depends on your specific use case and coding style.