Skip to content

Instantly share code, notes, and snippets.

@maxwellnewage
Created July 10, 2018 21:20
Show Gist options
  • Save maxwellnewage/51ec3d262d74086e31198382186ce09b to your computer and use it in GitHub Desktop.
Save maxwellnewage/51ec3d262d74086e31198382186ce09b to your computer and use it in GitHub Desktop.
generic class for resources controllers on Laravel
<?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