Back to Course |
Build Laravel API for Car Parking App: Step-By-Step

Get Parking Zones

Ok, after we've covered so much, this will be a very easy and quick one.

We need to have a list of the parking zones/areas, to show them in the application and to allow the user to choose where to start parking.

This will be only one public API endpoint: GET /api/v1/zones

So, let's generate a Controller:

php artisan make:controller Api/V1/ZoneController

Also, we generate the API Resource:

php artisan make:resource ZoneResource

We return only two relevant fields in that API Resource:

app/Http/Resources/ZoneResouce.php:

class ZoneResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price_per_hour' => $this->price_per_hour,
];
}
}

Inside the Controller, we will have only one method, for now:

app/Http/Controllers/Api/V1/ZoneController.php:

class ZoneController extends Controller
{
public function index()
{
return ZoneResource::collection(Zone::all());
}
}

A few things to note here:

  • Although there is one method, I don't use a Single Action Controller here with __invoke(), because it's a pretty big probability that there would be more methods in the future
  • In this case, we could avoid using the API Resource because it's not a reusable structure. That said, API Resources automatically add "data" as a wrapper, so for the sake of consistency, we do use API resources everywhere in the project, except for the Auth features.

We add this line into the public section of the routes:

routes/api.php:

use App\Http\Controllers\Api\V1\ZoneController;
 
Route::middleware('auth:sanctum')->group(function () {
// ... profile and vehicles
});
 
Route::post('auth/register', Auth\RegisterController::class);
Route::post('auth/login', Auth\LoginController::class);
 
Route::get('zones', [ZoneController::class, 'index']);

Since we had seeded the zones inside of the migration earlier, our API endpoint should give us the result:

Laravel API Zones

So, with all the preparations done, it's time to actually park the cars, huh?