Skip to content

Add model helpers for clearing and reloading cached relationships#288

Merged
techmahedy merged 2 commits into
doppar:3.xfrom
techmahedy:techmahedy-3.x
Jul 24, 2026
Merged

Add model helpers for clearing and reloading cached relationships#288
techmahedy merged 2 commits into
doppar:3.xfrom
techmahedy:techmahedy-3.x

Conversation

@techmahedy

Copy link
Copy Markdown
Member

Problem

Loaded relationships are cached on the model instance. If a many-to-many relationship is modified afterward, the model can continue returning stale data:

$post = Post::find(1);

$post->tags; // Loads and caches tags

$post->tags()->relate([1, 4]); // Updates the database

$post->tags; // Still returns the old cached tags

Solution

Added two methods to the base model:

$post->forget('tags');

Clears the cached relationship without executing a new query.

$post->reload('tags');

Clears the cached relationship and immediately loads the latest data from the database.

Example:

$post->tags()->relate([1, 4]);

$tags = $post->reload('tags');

Subsequent access also returns the refreshed relationship:

$post->tags; // Returns tags 1 and 4

Changes

  1. Added Model::forget(string $relation)
  2. Added Model::reload(string $relation)
  3. Added regression coverage for stale relationship data after relate()
  4. Preserved existing relationship caching behavior for normal access

@techmahedy techmahedy added the bug Something isn't working label Jul 24, 2026
@techmahedy
techmahedy merged commit bb48380 into doppar:3.x Jul 24, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant