Download the PHP package proai/laravel-struct without Composer
On this page you can find all versions of the php package proai/laravel-struct. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download proai/laravel-struct
More information about proai/laravel-struct
Files in proai/laravel-struct
Package laravel-struct
Short Description A Laravel package for using structs with Laravel including attribute casting.
License MIT
Homepage http://github.com/proai/laravel-struct
Informations about the package laravel-struct
Laravel Struct
A struct is a collection of typed variables. Structs are a well known datatype in other programming languages, but unfortunately not natively part of PHP yet. This package aims to bring structs to PHP and in particular to Laravel.
Installation
You can install the package via composer:
Please note that you need at least PHP 7.4 and Laravel 8 for this package.
Usage
The package uses named properties, which were introduced in PHP 7.4, to define a struct:
You can use all primitive types like string
, bool
, float
, int
, but also you can type a property as an object. The object can also be another struct, which enables you to nest structs (like GeoLocation
above).
Structs are instantiated by using an array of values:
Properties that are typed as objects will be converted to these objects on instantiation. Thus in the example above an object of App\Structs\GeoLocation
will be created for the $geo_location
property.
Properties can be accessed normally:
Hint: Snake cased properties are used to mimic the behaviour of Eloquent attributes.
Attribute Casting
You can use attribute casting with structs in your Eloquent models:
In order to make this work you need to define a json
column of the specified key, so in this case address
.
Alternatively you can use the composed struct caster by adding the argument composed
to compose a struct from multiple columns:
The column names must start with the specified key followed by an underscore and the property name. This also works with nested structs. For the example above we would need the following columns:
Finally you can also write your own custom caster by overwriting the castUsing
method of the struct like described in the Laravel docs.
Collections
Sometimes you need an array of structs. For this purpose you can define a struct collection. The struct collection class is inherited from the Laravel collection class, so you can use all methods of a Laravel collection.
By the way, attribute casting also works with struct collections for json
columns.
Support
Bugs and feature requests are tracked on GitHub.
License
This package is released under the MIT License.
All versions of laravel-struct with dependencies
illuminate/database Version ^10.0||^11.0
illuminate/support Version ^10.0||^11.0