Skip to content

Instantly share code, notes, and snippets.

@ndamnjanovic
Created October 28, 2013 14:34
Show Gist options
  • Save ndamnjanovic/7197749 to your computer and use it in GitHub Desktop.
Save ndamnjanovic/7197749 to your computer and use it in GitHub Desktop.
Extending Model using Laravel 4
Sometimes we need to extend out model, with more than data that is fetched from database, for example.
But on the other hand, we don't want to do that manually, and we want our framework to do that instead of us.
Here's an example, how to do that using Laravel 4.
Assume we have model Task, that has some fillable columns. Beside those, predefined columns, we want to attach additional data, let's say, parent task (and all its data).
First, we will define relationship between 'task' and 'task parent'. It is one-to-many relationship. We'll do it based on column named 'parent_id'.
public function parentTask(){
return $this->belongsTo('Task', 'parent_id');
}
Next step is to define accessor for this Model:
public function getParentTaskAttribute()
{
return $this->attributes['parent'] = $this->parentTask;
}
And finally, we need to define 'appends' property for this model:
protected $appends = array('parent_task');
Now we have it all.
Our model, will fetch both task data and parent task data.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment