diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index 7afa59933416..9eb6936e7374 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -577,6 +577,24 @@ public function forceFill(array $attributes) return static::unguarded(fn () => $this->fill($attributes)); } + /** + * Set the foreign key for a relationship to another model. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string|null $relationship + * @return $this + */ + public function for($model, $relationship = null) + { + $relationship ??= Str::camel(class_basename($model)); + + $foreignKey = $this->{$relationship}()->getForeignKeyName(); + + $this->forceFill([$foreignKey => $model->getKey()]); + + return $this; + } + /** * Qualify the given column name by the model's table. * diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index e7f249512bbd..070b40359a51 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -3178,6 +3178,29 @@ public function testCollectedByAttribute() $this->assertInstanceOf(CustomEloquentCollection::class, $collection); } + + public function testForCanSetForeignKeysForRelationships() + { + $post = new Post(); + $post->id = 123; + + $user = new DatabaseEloquentModelTestUser(); + $user->id = 456; + + $comment = (new Comment()); + $this->addMockConnection($comment); + + // Set some data so we can make sure "for" isn't clearing it. + $comment->content = 'Hello'; + + $comment + ->for($post) + ->for($user, 'user'); + + $this->assertSame($comment->content, 'Hello'); + $this->assertSame($comment->post_id, 123); + $this->assertSame($comment->the_user_id, 456); + } } class EloquentTestObserverStub @@ -3946,3 +3969,28 @@ class EloquentModelWithCollectedByAttribute extends Model class CustomEloquentCollection extends Collection { } + +class DatabaseEloquentModelTestUser extends Model +{ + protected $guarded = []; +} + +class Post extends Model +{ + protected $guarded = []; +} + +class Comment extends Model +{ + protected $guarded = []; + + public function post(): BelongsTo + { + return $this->belongsTo(Post::class); + } + + public function user(): BelongsTo + { + return $this->belongsTo(DatabaseEloquentModelTestUser::class, 'the_user_id'); + } +}