Should refresh() method load relations declared in $with variable? #40708
-
I've recently started working on a new Laravel application and I came across the following situation: class User extends Model
{
protected $with = ['profile'];
public function profile(): HasOne
{
return $this->hasOne(UserProfile::class);
}
} class UserProfile extends Model
{
protected $touches = ['user'];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
} class NewController extends Controller {
public function store()
{
// ..
$user = new User($userData);
$profile = new UserProfile($profileData);
$user->save();
$user->profile()->save($profile);
$user->refresh(); // <-- Here the "profile" relation is not going to be loaded, so $user->relationLoaded('profile') returns false
// $user->load('profile') // <-- You have to load the specific relation or do User::find($user->id);
return response()->json(['data' => $user], 201);
}
} Upon calling the I know that in Laravel's Docs the behaviour of the What do you think about altering the behaviour of the refresh method? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You are not loading the relation with calling |
Beta Was this translation helpful? Give feedback.
You are not loading the relation with calling
$user->profile()->save($profile);
if you look at the Model.php insideIlluminate\Database\Eloquent
it is loading the relations.