Pre-requisites
First, create your application
laravel new sanctum-example
laravel new sanctum-example
We'll assume 3 things:
Now open the YourController.php.
Develop the function destroy()
like this:
public function destroy(YourModel $yourmodel)
{
$yourmodel->delete();
return response()->noContent();
}
To test this in Postman, you'll need to send a DELETE 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 none instead of raw.
Try using an empty object to see if the API returns the validation message.
That should work.
We'll assume 3 things:
Http/Requests/UpdateYourRequest.php
.YourController.php
and remove the edit method.function update()
thus:public function update(UpdateYourRequest $request, YourModel $yourmodel)
http://localhost/api/yourcontroller/1
application/json
{
We'll assume 3 things:
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.
database/factories
.function definition()
, add the field names and the corresponding values to each field. Here's an example:public function definition(): array
public function run(): void
php artisan migrate --seed
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()