Skip to content

Instantly share code, notes, and snippets.

@browner12
Created November 15, 2014 01:22
Show Gist options
  • Save browner12/30dec0b2d70a088cdc9a to your computer and use it in GitHub Desktop.
Save browner12/30dec0b2d70a088cdc9a to your computer and use it in GitHub Desktop.
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

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