DEV Community

A0mineTV
A0mineTV

Posted on

1

🚀Building a Laravel API for Vehicle Management

Building a Laravel API for Vehicle Management

In this article, we’ll walk through creating a RESTful API in Laravel for managing vehicles. We’ll cover basic CRUD operations using Laravel's powerful resource system.


Prerequisites

Ensure you have the following set up:

  • Laravel 9+ installed.
  • A database configured in your .env file.
  • A Vehicle model and migration created.

You can generate the model and migration with:

php artisan make:model Vehicle -m
Enter fullscreen mode Exit fullscreen mode

Update your migration to define columns for model, rating, and company:

Schema::create('vehicles', function (Blueprint $table) {
    $table->id();
    $table->string('model');
    $table->integer('rating');
    $table->string('company');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Setting Up the Controller

Create a controller for the Vehicle resource:

php artisan make:controller VehicleController
Enter fullscreen mode Exit fullscreen mode

Here’s the updated controller with CRUD functionality:

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Resources\VehicleCollection;
use App\Http\Resources\VehicleResource;
use App\Models\Vehicle;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

final class VehicleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return VehicleCollection
     */
    public function index(): VehicleCollection
    {
        $vehicles = Vehicle::paginate(10);

        return new VehicleCollection($vehicles);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return Response
     */
    public function store(Request $request): Response
    {
        $validateData = $request->validate([
            'model' => 'required|string|max:255',
            'rating' => 'required|integer|min:1|max:5',
            'company' => 'required|string|max:255',
        ]);

        $vehicle = Vehicle::create($validateData);

        return response(new VehicleResource($vehicle), 201);
    }

    /**
     * Display the specified resource.
     *
     * @param Vehicle $vehicle
     * @return VehicleResource
     */
    public function show(Vehicle $vehicle): VehicleResource
    {
        return new VehicleResource($vehicle);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param Vehicle $vehicle
     * @return Response
     */
    public function update(Request $request, Vehicle $vehicle): Response
    {
        $validateData = $request->validate([
            'model' => 'sometimes|required|string|max:255',
            'rating' => 'sometimes|required|integer|min:1|max:5',
            'company' => 'sometimes|required|string|max:255',
        ]);

        $vehicle->update($validateData);

        return response(new VehicleResource($vehicle), 200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Vehicle $vehicle
     * @return Response
     */
    public function destroy(Vehicle $vehicle): Response
    {
        $vehicle->delete();

        return response(null, 204);
    }
}
Enter fullscreen mode Exit fullscreen mode

 Setting Up Resources

Use Laravel’s resource classes to structure your API response.

VehicleResource

<?php

declare(strict_types=1);

namespace App\Http\Resources;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use JsonSerializable;

final class VehicleResource extends JsonResource
{
    public static $wrap = 'vehicle';

    /**
     * Transform the resource into an array.
     *
     * @param  Request  $request
     * @return array|Arrayable|JsonSerializable
     */
    public function toArray($request): array|JsonSerializable|Arrayable
    {
        return [
            'model_name' => $this->model,
            'rating' => $this->rating,
            'company' => $this->company,
        ];
    }

    public function with($request): array
    {
        return ['status' => 'success'];
    }
}
Enter fullscreen mode Exit fullscreen mode

VehicleCollection

<?php

declare(strict_types=1);

namespace App\Http\Resources;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use JsonSerializable;

final class VehicleCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param Request $request
     * @return array|Arrayable|JsonSerializable
     */
    public function toArray($request): array|JsonSerializable|Arrayable
    {
        return [
            'data' => VehicleResource::collection($this->collection)
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

Registering Routes

Update your routes/api.php to include:

use App\Http\Controllers\VehicleController;

Route::resource('vehicle', VehicleController::class);
Enter fullscreen mode Exit fullscreen mode

Testing the API

You can test the API endpoints using tools like Postman or cURL. The endpoints include:

  • GET /api/vehicles - List all vehicles.

  • POST /api/vehicles - Create a new vehicle.

  • GET /api/vehicles/{id} - Show a specific vehicle.

  • PUT /api/vehicles/{id} - Update a specific vehicle.

  • DELETE /api/vehicles/{id} - Delete a specific vehicle.


Conclusion

This tutorial provides a simple yet effective way to build a Laravel API for vehicle management using resources and controllers. Feel free to customize the fields and validation rules based on your requirements.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay