Created
November 15, 2014 01:22
-
-
Save browner12/30dec0b2d70a088cdc9a to your computer and use it in GitHub Desktop.
Auto Callback for Relationship Collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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){ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could just use a mutator or an observer...