The laravel-datamapper provides a middleware that is able to convert an entity kind passed by request or url path to its respective model object . Take a look at contributing.md to see a to do list.
Via Composer
$ composer require agilize/laravel_datamapper
To allow Laravel Datamapper for all your routes, add the DataMappingMiddleware
middleware at $middleware
or $routeMiddleware
property of app/Http/Kernel.php
class:
protected $middleware = [
\Agilize\LaravelDataMapper\DataMappingMiddleware::class,
// ...
];
or
protected $routeMiddleware = [
'datamapping' => \Agilize\LaravelDataMapper\DataMappingMiddleware::class,
// ...
];
and add it in your routes:
Route::get('/user/{id}', function (Request $request) {
// ...
})->middleware('datamapping');
The middleware will search for a matching Model referencing the key passed on path, query string or parameter bag.
Eg.: http://yourdomain.com/api/v1/user/1 will search for User.php (instance of Eloquent ORM Model) that exists on your database with id 1
.
See Configuration for more details.
It also supports hyphen and underscore separated names. Eg.: http://yourdomain.com/api/v1/user-role/1 => UserRole.php
By default, the middleware is set to bring all existent relationships from Model. However, you need to create a withAll
scope in your model:
public function scopeWithAll($query)
{
$query->with('relation1', 'relation2');
}
If you don't want to bring any relationships from your Model, you can add a middleware parameter in your route to disable it:
Route::get('/user/{id}', function (Request $request) {
// ...
})->middleware('datamapping:no-relations');
The defaults are set in config/datamapping.php
. Publish the config to copy the file to your own config:
php artisan vendor:publish --tag="datamapping"
Option | Description | Default value |
---|---|---|
entity_directory | Default path to model directory of your project, eg. app_path('Packages') . |
string |
primary_key_type | Default primary key type of your database tables, eg. 'integer' or 'uuid' . |
string |
api_version | Main version of your REST API, eg. 'v1' . |
string |
$ composer test
RuntimeException: DataMapping config `some_key` should be a string.
RecursiveDirectoryIterator::__construct(...) error.
Any other not supported or invalid configuration may not cause an Exception, but will not attempt to exactly match the Model.
Please see contributing.md for details and a todolist.
Released under the MIT License. Please see the license for more information.