Create Controller:
php artisan make:controller Api/V1/SportsController
Create API Resource:
php artisan make:resource SportsResource
Add API Routes in
routes/api.php
:
use App\Http\Controllers\Api\V1\SportsController;
...
Route::apiResource('sports', SportsController::class)
->only(['index', 'show']);
- Open Controller (
app/Http/Controllers/Api/V1/SportsController.php
) and add the methods like the following:
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\SportsResource;
use App\Models\Sport;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class SportsController extends Controller
{
/**
* Display a listing of the resource.
*
* @response AnonymousResourceCollection<SportsResource>
*/
public function index(): AnonymousResourceCollection
{
return SportsResource::collection(Sport::paginate());
}
/**
* Display the specified resource.
*/
public function show(string $id): SportsResource
{
return new SportsResource(Sport::findOrFail($id));
}
}
- Open the API Resource (
app/Http/Resources/SportsResource.php
) and define the fields from the DB omittingdeleted_at
:
...
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
...
Top comments (0)