Tuesday 18 June 2024

Updating data using the API Resource to a Laravel 11 Model

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.
  4. That an Eloquent API Resource has been set up using this blog post.

Similar to the approach to add data we will update the Http/Requests/UpdateYourRequest.php.
We can begin by removing everything from within the class.
The we will instead extend the class by StoreYourRequest
Now open the YourController.php and remove the edit method.
In the function update() thus:
public function update(UpdateYourRequest $request, YourModel $yourmodel)
{
$yourmodel->update($request->validated());
return YourResource::make($yourmodel);
}
To test this in Postman, you'll need to send a PUT request with the URL of http://localhost/api/yourcontroller/1
In the Headers tab add the key Accept and the value of application/json
In the body select raw and choose the data format JSON.
Try using an empty object to see if the API returns the validation message
Now try an object like this:
{
"name": "My name again"
}
That should work.

Adding data using the API Resource to a Laravel 11 Model

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.
  4. That an Eloquent API Resource has been set up using this blog post.

This exercise will include adding validation of the incoming data.

When we created the model, we selected Form Requests, which created Http/Requests/StoreYourModelRequest.php and Http/Requests/UpdateYourModelRequest.php.

A Form Request in Laravel is a class that encapsulates the validation logic for a form submission. It allows you to separate the validation logic from your controller and makes it easier to reuse the same validation rules across multiple controllers.

We will edit StoreYourModelRequest.

If we're not using authorization the function authorize() should return true.

Now we will validation rules to the name field, thus:

public function rules()

{

return [

'name' => 'required|string|max:255'

];

}

Now in the YourController, we don't need the create method, so delete it. We just need to have a function store() which looks like this:

public function store()

{

$yourmodel = YourModel::create($request->validated())

return YourResource::make($yourmodel);

}


Now in the your model add the attribute

protected $fillable = ['name'];

$fillable is used to prevent unauthorised data manipulation by limiting which attributes can be set on a model.

To test this in Postman, you'll need to send a POST request with the URL of http://localhost/api/yourcontrollername

In the Headers tab add the key Accept and the value of application/json

In the body select raw and choose the data format JSON.

Try using an empty object to see if the API returns the validation message

Now try an object like this:

{

"name": "My name"

}

That should work.

Using the Eloquent API Resource to streamline data transferred by a Laravel 11 API Model


Eloquent is an Object-Relational Mapping (ORM) system that comes bundled with the Laravel PHP framework. It provides a simple and intuitive way to interact with your database using PHP. Eloquent allows you to define models, which are essentially classes that represent a single table in your database.

Pre-requisites

We'll assume 3 things:

  1. That the model was created using the approach in this blog post.
  2. That the route was created using the approach in this blog post.
  3. That a migration file has been set using this blog post.

Using the Eloquent API Resource to streamline data transferred by a Laravel 11 API Model

The Eloquent API Resource acts as a transformation layer between your eloquent models and the JSON responses. The object of this exercise is to specify only the fields we want to return to the requester, and contain the data within a data object.

To create an API resource run:

php artisan make:resource YourResource

Now the file is in the Resources directory.

Go to the Http/Resources/YourResource.php file

We will edit the function toArray()

This time we will return an associative array of fields e.g.

public function toArray(Request $request): array

{

return [

'id' => $this->id,            

'name' => $this->name,

// Note no description

        ];

}

Listing data using the API Resource

Our next step is to change the function index() in YourController.php, this time returning

YourResource::collection(YourModel::all());

Seeding migrations using factories for a Laravel 11 API Model

Seeding in Laravel is a process that allows you to insert dummy or sample data into a database. 
A factory is a feature that allows you to create fake data for your models, making it easier to test and seed your database with dummy data. Factories are particularly useful for testing, as they provide a way to create predictable and controlled data for your tests.
You'll see below that a factory is set up which describes the type of fake data to be produced during the migration.
Then, in the database seeder, this factory will be called upon for its description, when creating the seeds.

Pre-requisites

We'll assume 3 things:
That the model was created using the approach in this blog post.
That the route was created using the approach in this blog post.
That a migration file has been set using this blog post.

Factory

Now you can open the factory created for your model under database/factories.
This is a good place to add some seed definitions.
In the function definition(), add the field names and the corresponding values to  each field. Here's an example:
public function definition(): array
{
return [
    'name' => $this->faker->name(),
    'description' => $this->faker->sentence(20),
];
}

Seeds

In order to make use of the seed definition you created above, open seeders/DatabaseSeeder.php
public function run(): void
{
YourModel::factory(10)->create();
}

Now in the terminal:
php artisan migrate --seed

Now check in MySQL that the data has been created.
If you followed this blog post the function index(), had some test output of "Hello world" which we tested in Postman. Now we're going to add a listing of the records from our model within our controller and return that as JSON instead. Look for your controller in Http/Controllers/ then edit thus:
public function index()
{
return YourModel::all();
}

Setting up Migrations for a Laravel 11 API Model

Migrations in Laravel are a way to change the schema of a database in an organized and version-controlled manner. They provide a way to easily share the schema of the database and make modifications to it. Migrations are like creating a schema once and then sharing it many times.

Pre-requisites

We'll assume that the model was created using the approach in this blog post.

When the model was created in the pre-requisite, a migration file was also created for our model in the directory database/migrations.

It is in this file that we set the field types which will be populated as records are used within CRUD operations and listings. Below are examples of how these should be set in order to facilitate this:

public function up(): void

{

Schema::create('yourmodel', function (Blueprint $table) {

    $table->id();

    $table->string('name');

    $table->text('description')->nullable();

    $table->timestamps();

});

}

public function down(): void

{

Schema::dropIfExists('yourmodel');

}

It would be possible to run the migrations as is though:

php artisan migrate

but we may be best served, by seeding these migrations as we run them in order to have some test data.

 

Create Routes for a Laravel 11 API Model

Laravel routes are used to bind URLs to controller actions. REST methods are often used to describe the type of HTTP action which the route will respond to. 

Pre-requisites

Check to see if you already have a routes/api.php for this model.
This should have been created by running:
php artisan install:api

Now create a route for our class:
Route::apiResource('/yourmodelname', YourController::class);
Now in the terminal:
php artisan route:list --path=api
This creates a list of all the endpoints. You may wish to make a copy of these.

Before we can test the endpoints, we should add a response in our controller. I like to add
return response()->json(['message' => 'Hello World!']);
to the public function index().

We should now be in a position to test our endpoints.
We should run the server as:
php artisan serve
Then use a tool like Postman to test the first endpoint.
Commonly, when working locally, this would take the form of a GET request to and endpoint of:
http://localhost:8000/api/yourcontrollername
We should now see some JSON showing the message "Hello world".

Create a controller for a Laravel 11 API Model

Pre-requisites

Check to see if you already have a controller for this model. 

When the model was created using the approach in this blog post, a controller was created.

By running:
php artisan make:controller
you are provided with a list of prompts:
  1. You're asked to give it a name. I like to give it the same name as the model I just created.
  2. You're asked to select the type of controller to create. For this example, I like to select API.
  3. You're asked to select the model that this API controller would be used for. Here I name the model I just created.