Skip to content

Latest commit

 

History

History
118 lines (83 loc) · 2.57 KB

README.md

File metadata and controls

118 lines (83 loc) · 2.57 KB

Payloads

tests codecov

This is an MVP/POC.

Summary

Classes with the #[Payload] attribute can be resolved from the container and are hydrated automatically with data from the request payload. This enables strong type hints and intellisense for request bodies while decoupling the payload from the Request.

Validation

The optional validation provided by Payloads is a thin, strongly typed, wrapper around Laravel's built-in validation.

Hydration

Instance

Create an instance of a class from request parameters:

use Nacoma\Payloads\Hydrators\Attributes\MakeInstance;

new class {
    #[MakeInstance]
    public SomeClass $someClass1;
    
    #[MakeInstance(SomeOtherConcrete::class)]
    public SomeClass $someClass2;
};

Arrays & Collections

The MakeList plugin assumes that the type is either an array or some type of collection that takes an array of items as the constructor parameter.

use Nacoma\Payloads\Hydrators\Attributes\MakeList;
use Illuminate\Support\Collection;

new class {
    /**
     * @var SomeClass[] 
     */
    #[MakeList(SomeClass::class)]
    public array $items1;
    
    
    #[MakeList(SomeClass::class)]
    public Collection $item2;
};

Models

Fetch a model from the database using FindModel.

use Nacoma\Payloads\Hydrators\Attributes\FindModel;

new class {
    #[FindModel]
    public User $user;
};

More Featured Example

use Nacoma\Payloads\Hydrators\Attributes\FindModel;use YourApp\Models\Country;
use Nacoma\Payloads\Rules\Attributes as Rule;
use Nacoma\Payloads\Payload;
use Nacoma\Payloads\Transformers\Attributes as Transform;

#[Payload]
class UpdateUser {
    public function __construct(
        #[Rule\Required]
        public string $name,
        
        #[Rule\Required]
        #[Rule\Min(13)]
        #[Rule\Max(120)]
        public int $age,
        
        #[Rule\Required]
        #[Rule\Exists('countries', 'id')]
        #[Transform\Rename('country_id')]
        #[FindModel]
        public Country $country,
    ) {
      //
    }
}
class UserController extends Controller {
    public function update(User $user, UpdateUser $payload)
    {
        dump($payload->country->id);
    }
}