PHP code example of denizgolbas / laravel-auto-relational-resources
1. Go to this page and download the library: Download denizgolbas/laravel-auto-relational-resources library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
denizgolbas / laravel-auto-relational-resources example snippets
namespace App\Http\Resources;
use DenizGolbas\LaravelAutoRelationalResources\Traits\HasRelationalResources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
use HasRelationalResources;
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
// Automatically merge relations
return $this->mergeRelations($data, $request);
}
}
namespace App\Http\Resources;
use DenizGolbas\LaravelAutoRelationalResources\AutoRelationalResource;
class UserResource extends AutoRelationalResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
$user = User::with(['posts', 'profile'])->find(1);
return new UserResource($user);
$users = User::with(['posts', 'profile'])->get();
return UserResource::collection($users);
'model_namespace' => 'App\\Models',
// or
'model_namespace' => 'Domain\\Models',
'resource_namespace' => 'App\\Http\\Resources',
// or
'resource_namespace' => 'Domain\\Http\\Resources',
'auto_load_relations' => true, // Relations are automatically merged
'max_depth' => null, // Infinite depth - all relations are resolved
'max_depth' => 0, // Same as null - infinite depth
'max_depth' => 3, // Maximum 3 levels deep
'allowed_empty_collections' => [
'bankTransactionLines',
'customerSlipLines',
],
return [
'version' => '1.0.0',
'auto_load_relations' => true,
'max_depth' => null, // Infinite depth
'model_namespace' => 'App\\Models',
'resource_namespace' => 'App\\Http\\Resources',
'allowed_empty_collections' => [
'bankTransactionLines',
'customerSlipLines',
],
];
bash
php artisan vendor:publish --tag=config --provider="DenizGolbas\LaravelAutoRelationalResources\AutoRelationalResourcesServiceProvider"