From f7ce2c3b49f31d8bda88e93f29e9f11f21a946dc Mon Sep 17 00:00:00 2001 From: Flobbo Date: Tue, 11 Apr 2017 11:03:57 +0200 Subject: [PATCH] Fixed nullcheck error Added create and update Added withRelationships --- src/Crudable/Crudable.php | 46 +++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/src/Crudable/Crudable.php b/src/Crudable/Crudable.php index c6ed358..5ad5439 100644 --- a/src/Crudable/Crudable.php +++ b/src/Crudable/Crudable.php @@ -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(); @@ -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(); @@ -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; + } + } \ No newline at end of file