Created
July 10, 2018 21:20
-
-
Save maxwellnewage/51ec3d262d74086e31198382186ce09b to your computer and use it in GitHub Desktop.
generic class for resources controllers on Laravel
This file contains hidden or 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\Controllers; | |
use Illuminate\Database\QueryException; | |
use Illuminate\Http\Request; | |
class APIController extends Controller | |
{ | |
public static function index($model, $relation = null) | |
{ | |
if($relation) | |
$obj = $model::all()->load($relation); | |
else | |
$obj = $model::all(); | |
$data = array( | |
'status' => 'success', | |
'data' => $obj | |
); | |
return response()->json($data, 200); | |
} | |
public static function store($model, Request $request) | |
{ | |
try { | |
$obj = new $model($request->all()); | |
$obj->save(); | |
$data = DataResponse::getDataSuccess($obj); | |
} catch (QueryException $exception) { | |
$data = DataResponse::getDataFail($exception->errorInfo[2]); | |
} | |
return response()->json($data, 200); | |
} | |
public static function destroy($id, $model) | |
{ | |
$model::destroy($id); | |
$data = array( | |
'status' => 'success', | |
'message' => 'object destroyed' | |
); | |
return response()->json($data, 200); | |
} | |
public static function update($id, Request $request, $model) | |
{ | |
$obj = $model::findOrFail($id); | |
$obj->update($request->all()); | |
$data = array( | |
'status' => 'success', | |
'message' => 'object modified', | |
'data' => $obj | |
); | |
return response()->json($data, 200); | |
} | |
public static function show($id, $model) | |
{ | |
$obj = $model::find($id); | |
$data = array( | |
'status' => 'success', | |
'data' => $obj | |
); | |
return response()->json($data, 200); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment