I'm proud to announce that our team has released a new small package: spatie/laravel-model-info. Let's take a look at what this package can do.
This package makes it easy to determine your model classes' attributes and relations.
use Spatie\ModelInfo\ModelInfo; $modelInfo = ModelInfo::forModel(YourModel::class); // returns the filename that contains your model $modelInfo->fileName; // returns the name of the table your models are stored in $modelInfo->tableName; // returns a collection of `Attribute` objects $modelInfo->attributes; // returns a collection of `Relation` objects $modelInfo->relations;
Here's how you can get information about the attributes:
// returns the name of the first attribute $modelInfo->attributes->first()->name; // returns the type of the first attribute (string, integer, ...) $modelInfo->attributes->first()->type;
Here's how you can get information about the relations
// returns the name of the first relation, e.g. `author` $modelInfo->relations->first()->name; // returns the type of the // first relation, eg. `BelongsTo` $modelInfo->relations->first()->type; // returns the related model of the // first relation, eg. `App\Models\User` $modelInfo->relations->first()->related;
Additionally, the package can also discover all the models in your application.
use Spatie\ModelInfo\ModelFinder; // returns a `Illuminate\Support\Collection` containing all // the class names of all your models. $models = ModelFinder::all();
Here's a screenshot of the package in action at the code base of freek.dev
When we scroll down, we can see the attributes of the
This package will be convenient when you're building tooling around Laravel that needs to know information about how the models look like. We will be using laravel-model-info ourselves under the hood in our laravel-data, typescript transformer, and upcoming php-type-graph packages.
This isn't the first package that our team has built. On our company website, check out all our open source packages in this long list. If you want to support us, consider picking up any of our paid products.