I'm building a simple timetracking App using Laravel 5 where I have two Laravel models, one called "User" and one called "Week"
The relationships are pretty simple:
Week.php:
public function user()
{
return $this->belongsTo('App\User');
}
User.php:
function weeks()
{
return $this->hasMany('App\Week');
}
Now, the User.php file also has a simple helper / novelty function called "getCurrentWeek()" that, as the name suggests, returns the current week
function getCurrentWeek()
{
$possibleWeek = $this->weeks->sortByDesc('starts')->all();
if(count($possibleWeek) != 0)
{
return $possibleWeek[0];
}
else
{
return null;
}
}
My problem is: If I create the very first week for a user and attach / relate it to the user like so:
$week = new Week;
//Omitted: Setting so attributes here ...
$week->user_id = $user->id;
$weeks->save()
$user->weeks()->save($week);
And then call the $user->getCurrentWeek();
method, that method returns null
, although a new week has been created, is related to the user and has been saved to the database. In my mind, the expected behaviour would be for getCurrentWeek()
to return the newly created week.
What am I misunderstanding about Eloquent here / doing just plain wrong?