use App\User; class ApiController extends Controller{ public $response; public $request; public $auth; public function __construct(ResponseFactory $response, Request $request, Guard $auth) { $this->response = $response; $this->request = $request; $this->auth = $auth; $this->currentUser = $this->auth->user(); } }
this is an internal request we only return the data if ($this->request->input('no-json')) return $data; $message['status'] = true; if (isset($data)) $message['data'] = $data; if (isset($message)) $message['message'] = $response_message; if (isset($error_code)) $message['error_code'] = $error_code; return $this->response->json($message, $status_code); }
* Send back response with data * * @return Response */ public function example1() { $sample_data_array = ['k1'=>'value1', 'k2'=>'value2']; return $this->respond($sample_data_array, 'Message'); } }
{ public function register() { $app = $this->app; $app->bind('\App\Repositories\Contracts\UsersInterface', function() { $repository = new \App\Repositories\UsersRepository(new \App\User); return $repository; }); } } * Register the service provider in the list of autoloaded service providers in config/app.php
function __construct(Model $model) { $this->model = $model; } public function create($data) { return $this->model->create($data); } public function find($id) { return $this->model->find($id); } public function delete($id) { return $this->model->destroy($id); } public function all() { return $this->model->all(); }
[ "We don't have that kind of resources" ] } STATUS 404 Not Found { "status": false, "error_code": 2234, "errors": [ "That resource doesn't exist" ] } STATUS 418 I'm a teapot { "status": false, "message": "I'm a teapot" } STATUS 500 Internal Server Error { "status": false, "message": "Class 'User' not found" }
$method = 'GET', $input, $no_json) { // Store the original input of the request $originalInput = \Request::input(); // Create request to the API, adding the no-json parameter, since it's an internal request $request = \Request::create($url, $method); // Replace the input with the request instance input \Request::replace($input); // Fetch the response if ($no_json){ $content = \Route::dispatch($request)->getContent(); $result = json_decode($content, 1); }else{ $result = \Route::dispatch($request)->getContent(); } // Replace the input again with the original request input. \Request::replace($originalInput); return $result; } public function withNoInput($url, $method = 'GET', $no_json = true){ $input = ['no-json'=>$no_json]; return $this->release($url, $method = 'GET', $input, $no_json); } } app/Http/InternalDispatcher.php