<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <channel> <title>laravel – Jake Forrester</title> <atom:link href="https://www.jakeforrester.com/tag/laravel/feed/" rel="self" type="application/rss+xml" /> <link>https://www.jakeforrester.com</link> <description>Personal Blog</description> <lastBuildDate>Thu, 20 May 2021 19:34:51 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod> hourly </sy:updatePeriod> <sy:updateFrequency> 1 </sy:updateFrequency> <generator>https://wordpress.org/?v=6.6.2</generator> <image> <url>https://www.jakeforrester.com/wp-content/uploads/2020/08/cropped-seems_potato_jake-32x32.png</url> <title>laravel – Jake Forrester</title> <link>https://www.jakeforrester.com</link> <width>32</width> <height>32</height> </image> <site xmlns="com-wordpress:feed-additions:1">181047172</site> <item> <title>Laraval Cyclical Relationships</title> <link>https://www.jakeforrester.com/2021/05/20/laraval-cyclical-relationships/</link> <comments>https://www.jakeforrester.com/2021/05/20/laraval-cyclical-relationships/#respond</comments> <dc:creator><![CDATA[Jake]]></dc:creator> <pubDate>Thu, 20 May 2021 19:34:51 +0000</pubDate> <category><![CDATA[Laravel]]></category> <category><![CDATA[laravel]]></category> <category><![CDATA[optimization]]></category> <guid isPermaLink="false">https://www.jakeforrester.com/?p=102</guid> <description><![CDATA[How to optimize cyclical relationships in Laravel to avoid excessive database queries]]></description> <content:encoded><![CDATA[ <p>Most of the time relationships are in Laravel are straight-forward. Things can become tricky when considering performance and cyclical relationships, however. We need to avoid both double-fetching the same data, and infinite loops.</p> <p>Consider the following relationships where a User can create Blog Posts which belong to them.</p> <pre class="wp-block-code"><code lang="php" class="language-php">class User extends Model { public function posts(): HasMany { return $this->hasMany(User::class); } } class Post extends Model { public function user(): BelongsTo { return $this->belongsTo(User::class); } }</code></pre> <p>Now let’s do something slightly unusual. Let’s say that when we output a post to the API, we need to check user information.</p> <pre class="wp-block-code"><code lang="php" class="language-php">class Post extends Model { public function user(): BelongsTo { return $this->belongsTo(User::class); } public function toArray(): array { $data = parent::toArray(); $data['should_highlight'] = (bool) $this->user->is_admin; return $data; } }</code></pre> <p>If the user relationship is loaded, this is no big deal. If it isn’t, then we have to fetch the User model from the database for every post we render. This is a massive hit to performance, but we can improve it by eager-loading the relationship as part of the original query in the controller.</p> <pre class="wp-block-code"><code lang="php" class="language-php">class PostController extends Controller { public function getPosts(): JsonResponse { $posts = Posts::orderBy('updated_at', 'DESC') ->limit(10) ->with('user') // Eager-load user relationship as 1 query. ->get(); // Great performance. Two queries flat. return response()->json($posts->toArray()); } }</code></pre> <p>The above controller will execute two queries. One will fetch all the posts, then collect all the distinct user ids and run a second query to fetch all the users. Laravel will attach these User models to the Post models as we would expect. </p> <h2 class="wp-block-heading">Enter the Cyclic Relationship</h2> <p>What if we wanted to load all the posts a single user made? We know the user information already when loading their posts, so it would make sense that the reverse mapping would already be done for us. As such, the following example makes sense that it would “just work.”</p> <pre class="wp-block-code"><code lang="php" class="language-php">class PostController extends Controller { public function getUserPosts(int $userId): JsonResponse { $user = User::whereId($userId) ->with('posts') ->firstOrFail(); // Horrible N+1 performance. return response()->json($user->posts->toArray()); } }</code></pre> <p>Turns out Laravel isn’t that smart. We specified we wanted a user’s posts loaded, so <code>$user->posts</code> is loaded. But <code>$user->posts[0]->user</code> has to hit the database again.</p> <h2 class="wp-block-heading">The Official Way is Broken</h2> <p>Luckily, Laravel has the ability to manually set a relationship. Unfortunately for us, it doesn’t work in this case.</p> <pre class="wp-block-code"><code lang="php" class="language-php">class PostController extends Controller { public function getUserPosts(int $userId): JsonResponse { $user = User::whereId($userId) ->with('posts') ->firstOrFail(); // This will crash :( $user->posts->each->setRelation('user', $user); return response()->json($user->posts->toArray()); } }</code></pre> <p>When running the above code, PHP segfaults due to an infinite loop. Laravel doesn’t seem to like that we’re iterating on a model’s children and setting a property to the parent (which doesn’t make sense to me since all objects are passed by reference in PHP, but it is what it is).</p> <h2 class="wp-block-heading">The Strange (But Easy) Solution</h2> <p>We can load a model’s relationships with those relationship’s relationship to the parent (what a mouth-full). It’s much easier to see in an example than try to explain in English.</p> <pre class="wp-block-code"><code lang="php" class="language-php">class PostController extends Controller { public function getUserPosts(int $userId): JsonResponse { $user = User::whereId($userId) ->with(['posts', 'posts.user']) // User -> Posts[] -> User. ->firstOrFail(); // This works with two queries! return response()->json($user->posts->toArray()); } }</code></pre> <p>As weird as it feels to load a User model with a relationship which includes the relationship to itself, it works perfectly. The query is no different than the first one since Laravel recognizes we already have that User loaded. It wont go to the database to look anything extra up, and will set the property correctly.</p> <p>This works on nested relationships as well, such as: <code>$user->with(['posts', 'posts.comments', 'posts.comments.post']);</code>.</p> ]]></content:encoded> <wfw:commentRss>https://www.jakeforrester.com/2021/05/20/laraval-cyclical-relationships/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">102</post-id> </item> </channel> </rss>