Skip to content

Instantly share code, notes, and snippets.

@beanmoss
Created April 18, 2015 12:12
Show Gist options
  • Save beanmoss/977e846fee4050ae11e5 to your computer and use it in GitHub Desktop.
Save beanmoss/977e846fee4050ae11e5 to your computer and use it in GitHub Desktop.
Playing with Laravel Lumen: simple RESTful trait.
<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
trait RestControllerTrait
{
public function index()
{
$m = self::MODEL;
return $this->listResponse($m::all());
}
public function show($id)
{
$m = self::MODEL;
if($data = $m::find($id))
{
return $this->showResponse($data);
}
return $this->notFoundResponse();
}
public function store(Request $request)
{
$m = self::MODEL;
try
{
$v = \Validator::make($request->all(), $this->validationRules);
if($v->fails())
{
throw new \Exception("ValidationException");
}
$data = $m::create(\Request::all());
return $this->createdResponse($data);
}catch(\Exception $ex)
{
$data = ['form_validations' => $v->errors(), 'exception' => $ex->getMessage()];
return $this->clientErrorResponse($data);
}
}
public function update($id)
{
$m = self::MODEL;
if(!$data = $m::find($id))
{
return $this->notFoundResponse();
}
try
{
$v = \Validator::make(\Request::all(), $this->validationRules);
if($v->fails())
{
throw new \Exception("ValidationException");
}
$data->fill(\Request::all());
$data->save();
return $this->showResponse($data);
}catch(\Exception $ex)
{
$data = ['form_validations' => $v->errors(), 'exception' => $ex->getMessage()];
return $this->clientErrorResponse($data);
}
}
public function destroy($id)
{
$m = self::MODEL;
if(!$data = $m::find($id))
{
return $this->notFoundResponse();
}
$data->delete();
return $this->deletedResponse();
}
protected function createdResponse($data)
{
$response = [
'code' => 201,
'status' => 'succcess',
'data' => $data
];
return response()->json($response, $response['code']);
}
protected function showResponse($data)
{
$response = [
'code' => 200,
'status' => 'succcess',
'data' => $data
];
return response()->json($response, $response['code']);
}
protected function listResponse($data)
{
$response = [
'code' => 200,
'status' => 'succcess',
'data' => $data
];
return response()->json($response, $response['code']);
}
protected function notFoundResponse()
{
$response = [
'code' => 404,
'status' => 'error',
'data' => 'Resource Not Found',
'message' => 'Not Found'
];
return response()->json($response, $response['code']);
}
protected function deletedResponse()
{
$response = [
'code' => 204,
'status' => 'success',
'data' => [],
'message' => 'Resource deleted'
];
return response()->json($response, $response['code']);
}
protected function clientErrorResponse($data)
{
$response = [
'code' => 422,
'status' => 'error',
'data' => $data,
'message' => 'Unprocessable entity'
];
return response()->json($response, $response['code']);
}
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
function rest($path, $controller)
{
global $app;
$app->get($path, $controller.'@index');
$app->get($path.'/{id}', $controller.'@show');
$app->post($path, $controller.'@store');
$app->put($path.'/{id}', $controller.'@update');
$app->delete($path.'/{id}', $controller.'@destroy');
}
rest('/user', 'App\Http\Controllers\UserController');
$app->get('/', function() use ($app) {
return $app->welcome();
});
<?php namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class UserController extends BaseController
{
use RestControllerTrait;
const MODEL = 'App\Models\User';
protected $validationRules = ['username' => 'required', 'name' => 'required', 'password' => 'required'];
}
@mehradsadeghi
Copy link

mehradsadeghi commented Jun 23, 2018

You can use "exists" validation rule instead of :
if (!$data = $model::find($id)) { return $this->notFoundResponse(); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment