Search code examples
phprestrestler

Restler 3 nested resources?


In restler, is is possible to use nested resources? For example, with restler I would do the normal /api/account/123 call to get that specific account. Now I want to get the clients that belong to that account. So I'd want to also call /api/account/123/client/456 for example to get the specific client for the specific account.


Solution

  • You can use manual routing to define such routes. See the following example

    use Luracast\Restler\RestException;
    
    class Accounts
    {
    
        /**
         * Get specific client for the given account
         *
         * @param int $id account id
         * @param int $client_id
         *
         * @throws RestException 404
         *
         * @return Client
         *
         * @url GET accounts/{id}/clients/{client_id}
         */
        public function getClient($id, $client_id)
        {
            $r = Client::where('account_id', '=', $id)->where('id', '=', $client_id)->firstOrFail();
            if (empty($r))
                throw RestException(404, 'Client is not found associated with the account');
            return $r;
        }
    
        /**
         * Get all clients associated with the given account
         *
         * @param int $id account id
         *
         * @return array {@type Client}
         *
         * @url GET accounts/{id}/clients
         */
        public function getClients($id)
        {
            return Client::where('account_id', '=', $id)->all();
        }
    
    }