PHP code example of surazdott / api-response

1. Go to this page and download the library: Download surazdott/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/ */

    

surazdott / api-response example snippets


use Api;

....

public function index()
{
    $posts = Post::take(10)->get();

    return Api::response('Data fetched successfully', $posts);
}

public function index()
{
    $posts = Post::take(10)->get();

    return api()->response('Data fetched successfully', $posts);
}

return api()->response('Operation completed successfully', $data = [], $status = 200);

// Result
{
    "success": true,
    "message": "Operation completed successfully",
    "data": []
}

public function index()
{
    $users = User::take(2)->get();

    return api()->success('Request processed successfully.', $users);
}

// Result
{
    "success": true,
    "message": "Request processed successfully.",
    "data": [
        {
            "id": 1",
            "name": "Suraj....",
        },
        {
            "id": 2",
            "name": "Rabin....",
        }
    ]
}

public function index()
{
    $users = UserResource::collection(User::active()->paginate(10));

    return api()->paginate('Data fetched successfully.', $users);
}

// Result
{
    "success": true,
    "message": "Data fetched successfully.",
    "data": [
        {
            "id": 1",
            "name": "Suraj....",
        },
        {
            "id": 2",
            "name": "Rabin....",
        }
    ],
    "links": {
        "first": "http://example.com/api/v1/users?page=1",
        "last": "http://example.com/api/v1/users?page=1",
        "prev": null,
        "next": null
    },
    "meta": {
        "total": 0,
        "current_page": 1,
        "total_pages": 1,
        "per_page": 10
    }
}

public function store()
{
    $user = User::create(['name' => 'Suraj']);

    return api()->created('Resource created successfully', $user);
}

// Result
{
    "success": true,
    "message": "Resource created successfully",
    "data": [
        {
            "id": 1,
            "name": "Suraj Datheputhe",
        }
    ]
}

public function foo()
{
    return api()->error('Bad request');
}

// Result
{
    "success": false,
    "message": "Bad request"
}

public function edit()
{
    if ($user->isNotAdmin()) {
        return api()->unauthorized('Authentication is e"
}

public function edit()
{
    if ($user->isNotAdmin()) {
        return api()->unauthorized('You do not have permission to access this resource.');
    }
}

// Result 
{
    "success": false,
    "message": "You do not have permission to access this resource"
}

public function edit()
{
    $post = Post::find(1);

    if (! $post) {
        return api()->notFound('Requested resource could not be found');
    }
}

// Result
{
    "success": false,
    "message": "Requested resource could not be found"
}

Route::fallback(function() {
    return api()->notAllowed('Method type is not currently supported');
});

// Result
{
    "success": false,
    "message": "Method type is not currently supporte."
}

public function login()
{
    $validator = Validator::make($request->all(), [
        'email' => 'alidation('Validation failed for the request.', $validator->errors());
    }
}

// Result 
{
    "success": false,
    "message": "Validation failed for the request",
    "errors": {
        "password": [
            "The password field is 

public function index()
{
    try {
        $users = \App\Models\User::find($id); // Undefined $id
    } catch (\Exception $e) {
        return api()->error('Invalid syntax for this request was provided');
    }
}

// Result
{
    "success": false,
    "message": "Invalid syntax for this request was provided"
}



namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use SurazDott\ApiResposne\Concerns\HasApiResponse;

class UserStoreRequest extends FormRequest
{
    use HasApiResponse;
    
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['

use SurazDott\ApiResponse\Exceptions\ApiResponseException;

public function login(Request $request)
{
    if ($user->isNotAdmin()) {
        throw new ApiResponseException('User must be an admin', 403);
    }
}

// Result
{
    "success": false,
    "message": "User must be an admin"
}

use SurazDott\ApiResponse\Exceptions\ApiValidationException;

public function validation(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => ['e,
    "message": "Validation failed for the request",
    "errors": {
        "email": [
            "The email field is 

php artisan vendor:publish --tag=api-response