Skip to content

Instantly share code, notes, and snippets.

@Xethron
Last active August 29, 2015 14:16
Show Gist options
  • Save Xethron/cffeb51addad74560f35 to your computer and use it in GitHub Desktop.
Save Xethron/cffeb51addad74560f35 to your computer and use it in GitHub Desktop.
What Laravel Scopes are made for...
<?php
// We had a relationship similar to the one below:
public function currentParameters()
{
return $this->hasOne('Parameter')->where('active_date', '<=', Carbon::now())->orderBy('active_date', 'DESC');
}
// This pretty much got the last active parameter for a specific model.
// However, sometimes we wanted to see into the future/past, which wasn't entirely possible.
// Especially if you wanted to eagerload it.
// The Solution:
private parameterDate;
public function currentParameters()
{
$date = $this->parameterDate ?: Carbon::now();
return $this->hasOne('Parameter')->where('active_date', '<=', $date)->orderBy('active_date', 'DESC');
}
public function scopeSetParameterDate($query, Carbon $date)
{
$this->parameterDate = $date;
}
// Which allowed you to do something in the lines of:
Model::setParameterDate(Carbon::parse('16 Feb 1990'))->with('currentParameters')->where(.......)->get();
// Result = Sexy ^^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment