Skip to content

Commit

Permalink
Fixed nullcheck error
Browse files Browse the repository at this point in the history
Added create and update
Added withRelationships
  • Loading branch information
Flobbo authored and Flobbo committed Apr 11, 2017
1 parent da472d8 commit f7ce2c3
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions src/Crudable/Crudable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

trait Crudable {

protected $relation;

protected $relation = [];
protected $withHasMany,$withBelongsToMany;
/**
* Get a single item or collection
* @param int $id
* @return Model/Collection
*/
public function get($id = null){
if(is_null($id)){
if(!is_null($id)){
return $this->find($id);
}
return $this->model->with($this->relation)->get();
Expand All @@ -33,7 +33,7 @@ public function find($id){
* @return Model/Collection
*/
public function getTrash($id = null){
if(is_null($id)){
if(!is_null($id)){
return $this->getTrashedItem($id);
}
return $this->model->onlyTrashed()->with($this->relation)->get();
Expand All @@ -58,4 +58,42 @@ public function setRelation(array $relation){
return $this;
}

public function create(array $data, $relationName = null){
$model = $this->model->create($data);
//check for hasMany
if(!is_null($this->withHasMany) && !is_null($relationName)){
$model->{$relationName}()->saveMany($this->withHasMany);
}
//check for belongsToMany
if(!is_null($this->withBelongsToMany) && !is_null($relationName)){
$model->{$relationName}()->sync($this->withBelongsToMany);
}
return $model;
}

public function udpate(array $data){
return $this->model->update($data);
}

public function delete($id, $hardDelete = false){
$model = $this->model->find($id);
if($hardDelete){
return $model->forceDelete($id);
}
return $model->delete($id);
}

public function withHasMany(array $data, $relatedModel){
$this->withHasMany = [];
foreach($data as $k=>$v){
$this->withHasMany[] = new $relatedModel($v);
}
return $this;
}

public function withBelongsToMany(array $data){
$this->withBelongsToMany = $data;
return $this;
}

}

0 comments on commit f7ce2c3

Please sign in to comment.