Last active
July 19, 2017 03:04
-
-
Save blegoh/38c103ddf3918d858904e24594def435 to your computer and use it in GitHub Desktop.
Trait For API CRUD Resources
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 | |
namespace App\Http\Traits; | |
use Illuminate\Http\Request; | |
use Validator; | |
trait API | |
{ | |
protected $errorMessage = ''; | |
protected $error = false; | |
private function response($message,$data) | |
{ | |
$respon = [ | |
'error' => false, | |
'message' => $message, | |
'data' => $data | |
]; | |
return response()->json($respon); | |
} | |
private function responseError($message,$code) | |
{ | |
$respon = [ | |
'error' => true, | |
'message' => $message, | |
'data' => null | |
]; | |
return response()->json($respon,$code); | |
} | |
private function validation(Request $request,$type,$model = null) | |
{ | |
$rules = ($type == 'store') ? $this->model::$rulesCreate : $this->model::rulesEdit($model); | |
$validator = Validator::make($request->all(), $rules); | |
if ($validator->fails()) { | |
$this->error = true; | |
foreach ($validator->errors()->all() as $error){ | |
$this->errorMessage .= $error."\n"; | |
} | |
} | |
} | |
public function index() | |
{ | |
$datas = $this->model::all(); | |
return $this->response("success",compact('datas')); | |
} | |
public function store(Request $request) | |
{ | |
$this->validation($request,'store'); | |
if ($this->error){ | |
return $this->responseError($this->errorMessage,422); | |
} | |
$data = new $this->model; | |
foreach ($request->all() as $key => $value) { | |
$data->$key = $value; | |
} | |
if($data->isUser()){ | |
$data->user_id = auth()->user()->id; | |
} | |
$data->save(); | |
return $this->response("stored",compact('data')); | |
} | |
public function show($id) | |
{ | |
$data = $this->model::find($id); | |
return $this->response("success",compact('data')); | |
} | |
public function update(Request $request, $id) | |
{ | |
$data = $this->model::find($id); | |
$this->validation($request,'update',$data); | |
if ($this->error){ | |
return $this->responseError($this->errorMessage,422); | |
} | |
$data->update($request->all()); | |
return $this->response("updated",compact('data')); | |
} | |
public function destroy($id) | |
{ | |
$this->model::destroy($id); | |
return $this->response("deleted",null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment