Extending Laravel Controllers
I’ve been working for a while with PHP, using Laravel, and having started from the bottom, I must say, I am excited to be here!!!
What I’ve learned
When working with web controllers and trying to return JSON, I write code like:
return response()->json([ message => 'success' ]);
which makes sure that an HTTP 200 response is sent to the client, with the data:
{ "message": "success" }
Something I noticed
If we wanted to return an HTTP 404 response, we’d do stuff like:
return response()->json([ message => 'not found' ], 404);
It feels a little verbose, and we’re repeating code, especially the HTTP status code values.
What I did
Since every controller inherits from the BaseController
, we can create our own Controller
class to serve as our base.
class Controller extends BaseController {
use ...;
}
In this controller, we can create a public function called notFound
that returns a 404 JSON response.
public function notFound() {
return response()->json([
'message' => 'not found'
], 404);
}
What this means
Every controller that extends our Controller
class can then use:
return $this->notFound();
to return an HTTP 404 response, which is less verbose and easily readable.
The Potential
You could decide to pass parameters into your response functions like:
public function notFound($message = null) {
return response()->json([
'message' => $message ?? 'not found'
], 404);
}
So you can have code like:
return $this->notFound('foo not found');
Also, HTTP 404 is not the only response we can wrap this way. We can have fun doing this for:
400 Bad Request
public function badRequest($message = null) {
return response()->json([
'message' => $message ?? 'invalid request'
], 400);
}
Which can be used like:
return $this->badRequest();
500 Internal Server Error
public function error($message = null, Exception $ex) {
return response()->json([
'message' => $message ?? 'an error occurred',
'exception' => $ex
], 500);
}
Which can be used like:
return $this->error('sos');
So, have fun extending your controllers however you wish!!!