PHP code example of php-dev-umesh / laravel-api-response
1. Go to this page and download the library: Download php-dev-umesh/laravel-api-response library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
php-dev-umesh / laravel-api-response example snippets
use PhpDevUmesh\LaravelApiResponse\Facades\ApiResponse;
// In any controller or route:
ApiResponse::success($user, 'user.found');
// → {success: true, status: 200, message: "User found", data: {...}}
ApiResponse::error('user.not_found', 404);
// → {success: false, status: 404, message: "User not found", data: null}
use PhpDevUmesh\LaravelApiResponse\Traits\ApiResponseTrait;
class UserController extends Controller
{
use ApiResponseTrait;
public function index()
{
return $this->paginated(User::paginate(), 'users.loaded');
}
public function store(StoreUserRequest $request)
{
return $this->created(User::create(...), 'user.created');
}
}
'lang_replace' => ['app_name' => 'MyApp'],
// Merged with any per-call replacements
namespace App\Exceptions;
use PhpDevUmesh\LaravelApiResponse\Exceptions\RendersApiExceptions;
use Throwable;
class Handler extends ExceptionHandler
{
use RendersApiExceptions;
public function render($request, Throwable $e)
{
// Try API rendering first, fall back to Laravel's default
return $this->renderApiException($request, $e) ?? parent::render($request, $e);
}
}
use PhpDevUmesh\LaravelApiResponse\Exceptions\ApiException;
throw ApiException::make('user.not_found', 404);
throw ApiException::validationFailed($validator->errors());
throw ApiException::notFound('User');
throw ApiException::serverError('Something went wrong');
// Guard methods (throw on condition):
ApiException::throwIf($user->isBanned(), 'Account blocked', 403);
ApiException::throwIfNotSave($user->save());
ApiException::throwIfEmpty($collection);
use PhpDevUmesh\LaravelApiResponse\Http\ApiFormRequest;
class StoreUserRequest extends ApiFormRequest
{
public function rules(): array
{
return [
'email' => '