Created
March 17, 2017 20:03
-
-
Save str/1159f597d4a57b7986367087771dc933 to your computer and use it in GitHub Desktop.
Just extend the class and define $this->modelClass = YourSpecificModel::class;
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\Http\Request; | |
use App\Http\Requests; | |
abstract class AbstractRestController extends Controller | |
{ | |
protected $modelClass; | |
protected $orderBy = 'name'; | |
public function __construct() | |
{ | |
if (!$this->modelClass) throw new \Exception('Incomplete implementation of AbstractRestController, please define protected $modelClass'); | |
} | |
/** | |
* Display a listing of the resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function index() | |
{ | |
$query = \call_user_func([$this->modelClass, 'query']); | |
/* @var $query \Illuminate\Database\Eloquent\Builder */ | |
$resources = $query->orderBy($this->orderBy)->get(); | |
return response()->json($resources, 200); | |
} | |
/** | |
* Show the form for creating a new resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function create() | |
{ | |
// | |
} | |
/** | |
* Store a newly created resource in storage. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function store(Request $request) | |
{ | |
// | |
} | |
/** | |
* Display the specified resource. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function show($id) | |
{ | |
// | |
} | |
/** | |
* Show the form for editing the specified resource. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function edit($id) | |
{ | |
// | |
} | |
/** | |
* Update the specified resource in storage. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function update(Request $request, $id) | |
{ | |
$model = \call_user_func([$this->modelClass, 'find'], $id); | |
$data = $request->json()->all(); | |
foreach ($data as $key => $value) { | |
$model->{$key} = $value; | |
} | |
$model->save(); | |
return response()->json($model, 200); | |
} | |
/** | |
* Remove the specified resource from storage. | |
* | |
* @param int $id | |
* @return \Illuminate\Http\Response | |
*/ | |
public function destroy($id) | |
{ | |
// | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment