PHP code example of satheez / api-response
1. Go to this page and download the library: Download satheez/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/ */
satheez / api-response example snippets
namespace App\Http\Controllers\Api;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return JsonResponse
*/
public function index()
{
// todo, paginate the user data
return api()->success(User::all()->toArray());
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return JsonResponse
*/
public function store(Request $request): JsonResponse
{
// todo validate the request data
$user = User::create($request->all());
return api()->created($user->toArray());
}
/**
* Display the specified resource.
*
* @param int $id
* @return JsonResponse
*/
public function show($id): JsonResponse
{
$user = User::find($id);
// todo update process
return !empty($user)
? api()->success($user->toArray())
: api()->notFound();
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return JsonResponse
*/
public function update(Request $request, $id): JsonResponse
{
// todo update process
return api()->stored(User::find($id)->toArray());
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return JsonResponse
*/
public function destroy($id): JsonResponse
{
User::destroy($id);
return api()->deleted();
}
}
bash
php artisan vendor:publish --tag="api-response-config"