|
<?php |
|
|
|
namespace App\Http\Controllers; |
|
|
|
use Illuminate\Http\Request; |
|
|
|
trait RestfulControllerTrait |
|
{ |
|
/* |
|
* For save restful api index method paginate default page size. |
|
*/ |
|
private $perPage = 10; [60/677] |
|
|
|
/* |
|
* Get target controller's: |
|
* 1. model Eloquent. |
|
* 2. model rules. |
|
*/ |
|
public function __construct(Request $request) |
|
{ |
|
if (!isset($this->model)) { |
|
throw new Error("ModelNotSet"); |
|
} |
|
|
|
if (!isset($this->rules)) { |
|
throw new \Exception("RulesNotSet"); |
|
} |
|
} |
|
|
|
/* |
|
* Get resource list (paginate). |
|
*/ |
|
public function index(Request $request) |
|
{ |
|
$perPage = $request['per_page'] ?: $this->perPage; |
|
|
|
$result = $this->model::paginate($perPage); |
|
return response()->json($result, 200); |
|
} |
|
|
|
/* |
|
* Get resource list (all). |
|
* You can remove this function named all. |
|
*/ |
|
public function all(Request $request) [29/677] |
|
{ |
|
$result = $this->model::all(); |
|
return response()->json(['data' => $result], 200); |
|
} |
|
|
|
/* |
|
* Get resource item with id. |
|
*/ |
|
public function show(Request $request, $id) |
|
{ |
|
$item = $this->model::findOrFail($id); |
|
return response()->json(['data' => $item], 200); |
|
} |
|
|
|
/** |
|
* For validate request. |
|
*/ |
|
public function validateRequest(Request $request) |
|
{ |
|
$this->validate($request, $this->rules); |
|
} |
|
|
|
/* |
|
* Create new resource item. |
|
*/ |
|
public function store(Request $request) |
|
{ |
|
$this->validateRequest($request); |
|
|
|
$item = $this->model; |
|
$this->setItem($request, $item); |
|
$item->save(); // $this->model::create($item); |
|
|
|
return response()->json([], 200); |
|
} |
|
|
|
/* |
|
* Update item that belongs to passed id. |
|
*/ |
|
public function update(Request $request, $id) |
|
{ |
|
$this->validateRequest($request); |
|
|
|
$item = $this->model::findOrFail($id); |
|
$this->setItem($request, $item); |
|
$item->save(); |
|
|
|
return response()->json([], 200); |
|
} |
|
|
|
/* |
|
* Delete item that belongs to passed id. |
|
*/ |
|
public function destroy(Request $request, $id) |
|
{ |
|
$item = $this->model::findOrFail($id); |
|
$item->delete(); |
|
return response()->json([], 200); |
|
} |
|
} |
@shusharin Yes, it is.
The goal of setItem function is that you can do something before create/update the record, can you write an example for this? Thank you.