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

oliverbusk's avatar

Laravel - Method with relationship query - n+1?

Hi there

So I have a website where users can upload documents. When a document is uploaded, it will be saved to a specific folder in my storage, like:

stream_token/document_unique_id/mydocument.pdf

In my Document model, I have created a simple method, that can be used to get the path for the specific document:

    /**
     * A Document belongs to a Stream.
     *
     * @return Illuminate\Database\Eloquent\Model
     */
    public function stream()
    {
        return $this->belongsTo(Stream::class);
    }

    /**
     * Get the path to the unique folder for the document
     *
     * @return string
     */
    public function getPath(string $subfolder = '')
    {
        return "{$this->stream->token}/{$this->unique_id}/{$subfolder}";
    }

Since the method uses the $this->stream->token, every time I use it in my application, like:

 Storage::url($document->getPath('original')

It will fire a query to the relationship stream():

select  * from `streams` where `streams`.`id` = 1 limit 1

I use this method a lot of places in my application, but it seems a bit... Weird to use it, as I know it needs to fire of a query to get the stream->token everytime.

Is there any way I can "pre-load" the token or something like that to improve it?

0 likes
2 replies

Please or to participate in this conversation.