DEV Community

Bagaskara Wisnu Gunawan
Bagaskara Wisnu Gunawan

Posted on

Create API in Laravel

  1. Create Controller:
    php artisan make:controller Api/V1/SportsController

  2. Create API Resource:
    php artisan make:resource SportsResource

  3. Add API Routes in routes/api.php:

use App\Http\Controllers\Api\V1\SportsController;
...
Route::apiResource('sports', SportsController::class)
    ->only(['index', 'show']);
Enter fullscreen mode Exit fullscreen mode
  1. 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));
    }
}

Enter fullscreen mode Exit fullscreen mode
  1. Open the API Resource (app/Http/Resources/SportsResource.php) and define the fields from the DB omitting deleted_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,
        ];
    }
...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)