Cast XML elements to PHP classes and Laravel Eloquent models
Casting allows you to transform XML elements into instances of your PHP classes or Laravel Eloquent models, making it easier to work with type-safe objects.
Cast XML elements to a class using the cast() method:
use Flowgistics\XML\XML;class Note{ public function __construct($data) { // Initialize from array }}$xml = XML::import('notes.xml') ->cast('note')->to(Note::class) ->get();// $xml->note is now a Note instance
Cast XML elements directly to Laravel Eloquent models:
use Illuminate\Database\Eloquent\Model;use Flowgistics\XML\XML;class Note extends Model{ protected $fillable = [ 'to', 'from', 'heading', 'body', 'completed_at', ];}$xml = XML::import('notes.xml') ->cast('note')->to(Note::class) ->get();// $xml->note is now a Note model instance// You can use all Eloquent methods$xml->note->save();
When casting to Eloquent models, the XML data is passed to the model’s constructor as an array, using the model’s $fillable properties.
For more control over the casting process, implement the Castable interface:
use Flowgistics\XML\Casts\Castable;class TextNote implements Castable{ public function __construct( public string $to, public string $from, public string $text ) {} public static function fromCast(array $data): Castable { return new TextNote( $data['to'], $data['from'], $data['body'] ); }}$xml = XML::import('notes.xml') ->cast('note')->to(TextNote::class) ->get();// $xml->note is now a TextNote instance
The Castable interface requires a single static method:
fromCast(array $data): Castable - Receives the XML element data as an array and returns an instance of the class
$xml = XML::import('notes.xml') ->cast('note')->to(Note::class) ->get();// $xml->note is now an array of Note instancesforeach ($xml->note as $note) { echo $note->to; // Each item is a Note instance}
IDE support - Better autocomplete and code intelligence
Validation - Validate data in the fromCast() method
Transformation - Transform data during casting
Eloquent features - Access relationships, scopes, and other Eloquent features
Make sure the XML structure matches the expected properties of your class. Missing keys will result in null values or errors depending on your class implementation.