php - eloquent: How to load and set model variables, inside the model itself? -
laravel documentation suggests following way set eloquent model:
$user = user::with($conditions)->first(); what if want set eloquent model inside model itself:
$user = new user(); $user->setup($conditions); // class definition class user extends eloquent{ public function setup($conditions){ // load current object table data // $this->where($conditions)->first(); // previous line output dangling, ok assign $this variable? } }
if you're extending eloquent model, may try following approach. assume have unique id column.
public function setup($conditions) { $model = self::with($conditions)->first(); if (! is_null($model)) { $this->exists = true; $this->forcefill(self::find($model->id)->toarray()); } return $this; } hope solve issue.
Comments
Post a Comment