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

TarikAli's avatar

is url path in model make a query ?

Hello, in Post model i use this method to get the path of current post

Post Model : public function path () { return url ( 'posts/'.{$this->id} ); }

when i make loop throw posts like

foreach ( $posts as $post) { $post->path }

is $post->path here will make another query to the database or will take the id from current $post of loop of course i'dont want to make another query because i already has it in $post of the loop . Thanks

0 likes
8 replies
rodrigo.pedra's avatar
Level 56

It will use the data already fetched, so It won't make another call to the DB,

Snapey's avatar

path is a public function, so it would need to be;

foreach ( $posts as $post) { $post->path() }

also, rewrite your function

public function path () 
{
    return url( 'posts/'. $this->id ); 
}
TarikAli's avatar

ok thanks Snapey . But you agree with RODRIGO.PEDRA that it will not make a new query ? . it will get the id from the post passed from loop

Snapey's avatar

Use something like Laravel Debugbar to check your queries. Its easy to get into an n+1 error. As we don't see the rest of your code, it is assumed that all Post models are fully hydrated.

TarikAli's avatar

$posts = post::where('category_id',1)->get(); n+1 error you mean eager loading ( like getting data with eloquent relations with word (with) )

Please or to participate in this conversation.