Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto Callback for Relationship Collection
<?php
class Car extends Eloquent {
//wheels relationship
public function wheels(){
return $this->hasMany('Wheel');
}
//current hack
public function getWheelsAttribute(){
//get wheels
$wheels = $this->wheels;
//callback
$wheels->each(function($wheel){
$wheel->turn(90);
});
//return wheels collection
return $wheels;
}
//proposed feature
//gets called automatically when laravel uses magic method on relationship
//naming convention is what allows it to automagically happen
public function wheelsCollectionCallback($wheels){
//callback
$wheels->each(function($wheel){
$wheel->turn(90);
});
//return wheels collection
return $wheels;
}
}
?>
<?php
//user doesn't need to change existing usage
$car = Car::find(1);
foreach($car->wheels as $wheel){
}
@devonzara
Copy link

devonzara commented Nov 15, 2014

You could just use a mutator or an observer...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment