Object Context
Each Data
class object has its own context throughout its lifecycle. This context dynamically manages the properties and behavior of the object, allowing you to include or exclude data from serialization on the fly.
Context Management Methods
exclude
The exclude
method allows you to exclude a property from the serialization result using dot notation for nested fields.
class UserRequesites extends Data {
public function __construct(
public string $country,
public string $phone_number
) {}
}
class User extends Data {
public function __construct(
public string $name,
public string $password_hash,
public UserDetails $requesitess
) {}
}
$requesites = new UserRequesites("UK", "+4402020000000");
$user = new User('John', "f4091876df6a5d39e6690b7395a95399", $requesites);
$user->exclude('password_hash', 'requesites.phone_number');
$data = $user->toArray();
/*
* $data: [
* "name" => "John",
* "requesites" => [
* "country" => "UK"
* ]
* ]
*/
include
The include
method explicitly marks a lazy or nested property to be included in the serialized output.
class User extends Data {
public function __construct(
public Lazy|UserProfile $profile;
) {}
}
$user = User::from([
'profile' => new Lazy(fn () => UserProfile::from($profileData))
]);
// Without calling include, the "profile" field won't be output
$user->include('profile');
$data = $user->toArray();
/* $data: [
* 'profile' => UserProfile
* ]
*/