skip to Main Content

For example, I develop an api and I have to type all my functions, I have a function that returns a list of movements, so how to define the return type of my function ? I tried to do this : public function getAllMovements() : Movement[] {} But it does’nt work, i work with laravel 10.

2

Answers


  1. I have defined a Movement Resource that return a movement collection

    class MovementResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  IlluminateHttpRequest  $request
         * @return array|IlluminateContractsSupportArrayable|JsonSerializable
         */
        public function toArray($request)
        {
            return parent::toArray($request);
        }
    }
    
    
    

    and in my function I have defined the resource as a return type and everything is working correctly

    public function getAllMouvements() : MovementResource {}
    
    

    With this we are sure that the return type will be a collection of movements.

    Login or Signup to reply.
  2. If you want it only available in documentation, it’s supported by phpdoc like so:

    /**
     * @return Movement[]
     */
    

    Else, I think you should create a strongly typed collection yourself, for example answered here: https://stackoverflow.com/a/73738459/3090890

    class MovementCollection extends ArrayObject
    {
        public function __construct(array $items = [])
        {
            foreach ($items as $item) {
                $this->validate($item)
            }
        }
        ... 
    

    In API’s its not uncommon to build typed collections like that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search