Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sebastian.virlan's avatar

Many to Many tables presenter

Hi, I have 3 main tables:

  • users
  • agents
  • clients

And one table:

  • documents

For each of the main tables I created a pivot one so I have:

  • user_documents
  • agent_documents
  • client_documents

So for each of this entities I must generate some URL for the documents to be downloaded and a preview thumb so I created a presenter for Documents model.

The problem is that I can't determine the entity in the presenter so I can generate the urls:


class DocumentPresenter extends Presenter
{

    public function url() {

        return url('clients/document/'.$this->model->id);  //clients is hardcoded but should be the plural of the model class (client, user, agent).

    }

    public function thumb() {

        if(substr($this->model->document_content_type, 0, 5) == 'image')
            return url('uploads/clients/'.$this->model->pivot->client_id.'/'.$this->model->document_file_name);  //here is the same but I have one more problem with the $this->model->pivot->client_id beucase client_id should be dinamic (agent_id, user_id)

        return url('/assets/platform/img/document.png');
    }
}

What I need is when I access the agent page I do:

$agent = Agent::find(5)->with('documents');

I wanna get all documents with url and thumb, and when I upload a document for an agent:

                $document = new Document();
                $document->document_file_name = $newDocumentName;
                $document->document_file_size = $imageSize;
                $document->document_content_type = $imageMime;
                $document->save();

                $document->agent()->attach($agent->id);
        return ['response' => $document, 'code' => 200];

I want the response to also contain the url and thumb.

To do this I added to Document model:

protected $appends = ['url', 'thumb'];

    public function getUrlAttribute() {

        return $this->present()->url;

    }

    public function getThumbAttribute() {

        return $this->present()->thumb;

    }

And is returned in both cases but as I explained I can't figure how to get the plural of the pivot class name and the pivot id to compose the url.

0 likes
0 replies

Please or to participate in this conversation.