Tuesday 18 June 2024

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.

No comments:

Post a Comment