It is generally considered good practice to keep your controllers as thin as possible and move as much logic as possible into separate classes. In this case, it would be a good idea to create a separate class to handle response messages.
Here's an example of what that might look like:
<?php
namespace App\Services;
class ResponseService
{
public function success($message, $data = [])
{
return response()->json([
'success' => true,
'message' => $message,
'data' => $data,
]);
}
public function error($message, $code = 400)
{
return response()->json([
'success' => false,
'message' => $message,
], $code);
}
}
You can then use this class in your controllers like this:
<?php
namespace App\Http\Controllers;
use App\Services\ResponseService;
class MyController extends Controller
{
protected $responseService;
public function __construct(ResponseService $responseService)
{
$this->responseService = $responseService;
}
public function index()
{
$data = [
'foo' => 'bar',
];
return $this->responseService->success('Data retrieved successfully', $data);
}
public function store()
{
// Do some validation and save the data
if ($saved) {
return $this->responseService->success('Data saved successfully');
} else {
return $this->responseService->error('Failed to save data', 500);
}
}
}
This approach has a number of benefits:
- Your controllers are simpler and easier to read, because they don't contain a lot of response logic.
- Your response logic is centralized in one place, making it easier to maintain and update.
- You can easily change the format of your response messages (e.g. to include more or less data) without having to update every controller method that returns a response.
Of course, this is just one possible implementation. You could also use a trait, a helper function, or some other approach to handle response messages. The important thing is to keep your code organized and easy to understand.