How to set a default value for a property. #416
Replies: 4 comments 3 replies
-
Support in Laravel Data is PHP's support for simple regular class property defaults, e.g.
For what you describe: duplicate of #414 |
Beta Was this translation helpful? Give feedback.
-
Hi @jonothedev :) If the source of true is coming from the model , Should we need default property in the dto ? Why not added default values in the models inserted ? |
Beta Was this translation helpful? Give feedback.
-
Hi, class User extends Data
{
public function __construct(
public string $username,
) {}
public static function createFromApiX(array $data): static
{
return static::from([
'username' => $data['first_name'] . '_' . $data['last_name'],
]);
}
}
$obj = User::createFromApiX([
'first_name' => 'foo',
'last_name' => 'bar',
]);
assert('foo_bar' === $obj->username); But I wonder if there's any drawbacks to this? One already is that I can't pass a json string directly like you can with |
Beta Was this translation helpful? Give feedback.
-
I've added some extra docs on default values + a computed value support, should be landing later today. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
How can we set a default value for a property? For example, if i were to create a data object, but set a value for a property from two other properties..
Then set a default value for username
$this->username = $this->first_name . '_' . $this->last_name;
Is this possible?
Beta Was this translation helpful? Give feedback.
All reactions