Skip to content

Instantly share code, notes, and snippets.

@moradi-morteza
Last active July 6, 2020 07:09
Show Gist options
  • Save moradi-morteza/4b14e7fc8ca0487ae972b247d2872984 to your computer and use it in GitHub Desktop.
Save moradi-morteza/4b14e7fc8ca0487ae972b247d2872984 to your computer and use it in GitHub Desktop.
[api Exception Handler]
// very important
1- use
Content-Type: application/json
Accept: application/json
** you should for every request set customRequest
in all of your api client request.
2- to avoid show server error in client
in Exception/Handler.php
public function render($request, Exception $exception)
{
if ($request->wantsJson()){
$exception=$this->prepareException($exception);
// use for validation exception if use validation
if ($exception instanceof ValidationException){
return response([
'errors'=>$exception->errors()
],422);
}
// user for authtication exceptions if use api auth
if ($exception instanceof AuthenticationException){
return response([
'errors'=>'Unauthorized'
],401);
}
$code = method_exists($exception,'getStatusCode') ? $exception->getStatusCode() : 500;
switch ($code){
case (500):
$message='Error';
break;
case (400):
$message='Bad Request';
break;
case (401):
$message='Unauthorized';
break;
case (403):
$message='Forbidden';
break;
case (404):
$message='Not Found';
break;
case (409):
$message='Conflict';
break;
default:
$message= $exception->getMessage();
}
return response(['message'=> $message],$code);
}
return parent::render($request, $exception);
}
3- in controller
public function show($id){
$posts=PostModel::findOrFail($id);
return $posts;
}
4- for more secure you can change the name of 'api' in RouteServiceProvider.php
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
// finaly you should code like this
class PostController extends Controller
{
public function index()
{
return PostModel::all();
/* do not code liek
$posts = PostModel::all();
return response($posts,200);
*/
}
public function show($id){
return PostModel::findOrFail($id)->user; // if you do not use find or fail it return null if data not exist
}
public function store(Request $request){
return PostModel::create($request->all()); // this can retrun a response with its currect status code (201) Created
}
public function update(Request $response, $id){
$post=PostModel::findOrFail($id);
$result_boolean=$post->update($response->all());
if ($result_boolean){
return response(null,202);
}else{
return response(null,500);
}
}
public function destroy($id){
$post= PostModel::findOrFail($id);
$result_boolean =$post->delete();
if ($result_boolean){
return response(null,204);
}else{
return response(null,500);
}
}
}
// sample for User
class UserController extends Controller
{
public function store(Request $request){
$user = User::create([
'name'=> $request->name,
'email'=> $request->email,
'password'=> bcrypt($request->password),
]
);
$user->password=bcrypt($request->password);
return $user;
}
public function show($id){
return User::findOrFail($id);
}
public function update(Request $request,$id){
$user= User::findOrFail($id);
// we want just update name or password not email so
$data = $request->only('name','password');
if (!empty($data['password'])){
$data['password']=bcrypt($data['password']);
}
$result_boolean=$user->update($data);
if ($result_boolean){
return response(null,202);
}else{
return response(null,500);
}
}
public function destroy($id){
$post= User::findOrFail($id);
$result_boolean =$post->delete();
if ($result_boolean){
return response([],204);
}else{
return response([],500);
}
}
}
/*
500 internall error
404 not found
200 successful wtih or without data (for action)
201 Created (for create)
202 Accepted ( for update)
204 succseful but without data (for remove)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment