For me, the data I want to retrieve may be in database for which I can use properties of model and also relationships, but if the record is not a property and no relationship exists for that particular record, I need to check it from an API end point, so where I should place my API request code, is it okay to put the code in model and when retrieving I will retrieve either from database or API depending on situation?

Note: API will not update or insert data in my database.

  • 2
    it's going to be hard to answer without more context. What can you tell about your current architecture, design, layers, whatever? A model can be literally anything in software engineering and be located in any place within a design. – Laiv Mar 19 at 9:51
  • @Laiv I have used Laravel in it as I have added the laravel tag, can you tell me what you want more about it, so that I can edit my question? – Prafulla Kumar Sahu Mar 19 at 10:28

In my opinion, you should add another abstract layer (for example, a repository) between the model and the client using it. I think it's better if we keep the model clean from infrastructure related code (quering database, calling API, ...). The following is my pseudo code, not in any specific language.

The repository interface

interface ModelRepositoryInterface {
    public Model getModelById(int id);

Start with a database repository:

class DatabaseModelRepository implement ModelRepositoryInterface {
    public Model getModelById(int id) {
        // query from database

Then add the API decorator over it:

class ApiDecoratedModelRepository implement ModelRepositoryInterface {
    private ModelRepositoryInterface baseRepository;

    constructor(ModelRepositoryInterface base) {
         this.baseRepository = base;

    public Model getModelById(int id) {
         Model dbModel = this.baseRepository.getModelById(id)
         if (dbModel is not null) then return dbModel;
         return this.getModelFromApi(id);

Your client should contains the reference to an instance of the API decorated repository when it want to retrieve a model instance. Dependency Injection is highly recommended to make the process of initialising repositories easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.