Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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'];
}
@meness

This comment has been minimized.

Copy link

commented Jan 31, 2017

I prefer to use the grouping routes feature instead of making methods.

@hiyali

This comment has been minimized.

Copy link

commented May 8, 2017

@meness look at this solution.

@mehradsadeghi

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.