How to update user through api in laravel - php

I'm trying to update user through api, and this is the function.
PUT request http://20a11140.ngrok.io/api/userregister/24 for user with id 24 for example.
I'm using postman for testing
When I pass the edited details, with name inclusive
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'string|min:6|confirmed',
'phone' => 'string|min:6',
'Age' => 'string',
'Blood' => 'string',
'Gender' => 'string',
'Height' => 'string',
'Weight' => 'string',
'record' => 'string'
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$doc = User::find($id);
if($request->hasFile('picture')){
// Get filename with the extension
$filenameWithExt = $request->file('picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('picture')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$doc->name = $request->input('name');
$doc->email = $request->input('email');
$doc->phone = $request->input('phone');
if($request->hasFile('picture')){
$doc->picture = $fileNameToStore;
}
$doc->save();
return response()->json([
'message' => 'Success',
]);
}
When I pass the edited details, with name inclusive and email, and every required info.
When I run this code, I get this
"{\"name\":[\"The name field is required.\"],\"email\":[\"The email field is required.\"]}"
What is the issue here?

Somewhere you are wrong with sending data.
If you are using API middlewares then you will have to send data with Body Raw Json using Postman.
{
"info": {
"_postman_id": "9bc0d91b-83e7-4ccf-a561-ac191c21e869",
"name": "Laravel",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "http://20a11140.ngrok.io/api/userregister/24",
"request": {
"method": "PUT",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n\t\"name\" : \"BHaskar Rajoriya\",\n\t\"email\" : \"brn.rajoriya#gmail.com\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://20a11140.ngrok.io/api/userregister/24",
"protocol": "http",
"host": [
"20a11140",
"ngrok",
"io"
],
"path": [
"api",
"userregister",
"24"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
}
Use this postman collection.

Related

Laravel "Required" Validation Causes Validation To Fail

I'm trying to validate data gathered from a json file. If I don't include the "required" validation, the validation passes, but when I add it back in it fails for some reason. I don't understand how it would be failing if all fields it's checking against aren't null.
Anything obvious that I'm missing?
Controller:
// START: Validate request
$validator = Validator::make($request->all(), [
'results.*.status.*.name' => 'required|max:255',
'results.*.error.*.name' => 'required',
'results.*.messageId' => 'required',
'results.*.doneAt' => 'required|date',
'results.*.smsCount' => 'required|numeric',
'results.*.sentAt' => 'required',
'results.*.callbackData' => 'required',
]); // The "required" is causing the validation to fail
if ($validator->fails()) {
dd('fail');
} else {
dd('pass');
}
// END: Validate request
Json data:
{
"results": [
{
"bulkId": "BULK-ID-123-xyz",
"price": {
"pricePerMessage": 0.0185,
"currency": "GBP"
},
"status": {
"id": 5,
"groupId": 3,
"groupName": "DELIVERED",
"name": "DELIVERED_TO_HANDSET",
"description": "Message delivered to handset"
},
"error": {
"id": 0,
"name": "NO_ERROR",
"description": "No Error",
"groupId": 0,
"groupName": "OK",
"permanent": false
},
"messageId": "MESSAGE_UUID",
"doneAt": "2022-11-21T17:11:16.661+0000",
"smsCount": 1,
"sentAt": "2022-11-21T17:11:12.129+0000",
"callbackData": "CAMPAIGN_ID",
"to": "447572554668"
}
]
}
You simply just have to replace this:
'results.*.status.*.name' => 'required|max:255|nullable',
'results.*.error.*.name' => 'required|nullable',
With this:
'results.*.status.*' => 'required|max:255|nullable',
'results.*.error.*' => 'required|nullable',
You are getting error because of there is no name key in status properties and you want them to be required.

Docusign Composite Template

We are working with docusign Composite Template API with PHP. We Tried to add a custom document with base64 encoded format with signHereTabs object with values. We are able to create envelope and views for recipient successfully.But the issue is it's not generating signHereTabs which we are tried for recipient. Can you please help us to resolve this issue?
Sample Request in json to create envelope:
{
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"clientUserId": "1000",
"name": "Full Name",
"email": "my email",
"recipientId": "1",
"roleName": "Sender",
"tabs": {
"signHereTabs": [
{
"anchorString": "\/sig1\/",
"anchorUnits": "pixels",
"anchorXOffset": "20",
"anchorYOffset": "10"
}
]
}
}
]
},
"customFields": {
"textCustomFields": [
{
"name": "MyOwnField",
"required": "true",
"show": "true",
"value": "MyValue"
}
]
}
}
],
"document": {
"documentBase64": "<base64 encoded string>",
"documentId": "1",
"fileExtension": "pdf",
"name": "Agreement.pdf",
"transformPdfFields": false
}
}
]
}
View Recipient sample request:
{
"document": {
"documentBase64": "<base64 encoded string>",
"documentId": "1",
"fileExtension": "pdf",
"name": "Agreement.pdf",
"transformPdfFields": false
}
}
The fields (tabs) need to be a part of the signers object.
Here's a working example from the API Request Builder:
{
"emailSubject": "Please sign the attached document",
"status": "sent",
"compositeTemplates": [
{
"compositeTemplateId": "1",
"document": {
"filename": "anchorfields.pdf",
"name": "Example document",
"fileExtension": "pdf",
"documentId": "1"
},
"inlineTemplates": [
{
"sequence": "1",
"recipients": {
"signers": [
{
"email": "signer_email#example.com",
"name": "Signer's name",
"recipientId": "1",
"clientUserId": "1000",
"tabs": {
"signHereTabs": [
{
"anchorString": "/sig1/",
"anchorXOffset": "20",
"anchorUnits": "pixels"
}
]
}
}
]
}
}
]
}
]
}
Here it is with the PHP SDK (auto-generated by the API Request Builder):
<?php # DocuSign Builder example. Generated: Sat, 03 Sep 2022 18:34:12 GMT
# DocuSign Ⓒ 2022. MIT License -- https://opensource.org/licenses/MIT
# #see DocuSign Developer Center
require_once ('vendor/autoload.php');
require_once ('vendor/docusign/esign-client/autoload.php');
# Note: the access_token is for testing and is temporary. It is only good for 8 hours from the time you
# authenticated with API Request Builder.
const base_uri = 'https://demo.docusign.net/';
const access_token = '';
const account_id = '';
const document_directory = '.'; # The directory with your documents, relative to this script's directory
#
function sendDocuSignEnvelope() {
$docs_path = getcwd() . '/' . document_directory . '/';
$document1 = new \DocuSign\eSign\Model\Document([
'document_id' => "1",
'file_extension' => "pdf",
'document_base64' => base64_encode(file_get_contents($docs_path.'anchorfields.pdf')), # filename is anchorfields.pdf
'name' => "Example document"
]);
$sign_here_tab1 = new \DocuSign\eSign\Model\SignHere([
'anchor_string' => "/sig1/",
'anchor_units' => "pixels",
'anchor_x_offset' => "20"
]);
$sign_here_tabs1 = [$sign_here_tab1];
$tabs1 = new \DocuSign\eSign\Model\Tabs([
'sign_here_tabs' => $sign_here_tabs1
]);
$signer1 = new \DocuSign\eSign\Model\Signer([
'client_user_id' => "1000",
'email' => "signer_email#example.com",
'name' => "Signer's name",
'recipient_id' => "1",
'tabs' => $tabs1
]);
$signers1 = [$signer1];
$recipients1 = new \DocuSign\eSign\Model\Recipients([
'signers' => $signers1
]);
$inline_template1 = new \DocuSign\eSign\Model\InlineTemplate([
'recipients' => $recipients1,
'sequence' => "1"
]);
$inline_templates1 = [$inline_template1];
$composite_template1 = new \DocuSign\eSign\Model\CompositeTemplate([
'composite_template_id' => "1",
'document' => $document1,
'inline_templates' => $inline_templates1
]);
$composite_templates1 = [$composite_template1];
$envelope_definition = new \DocuSign\eSign\Model\EnvelopeDefinition([
'composite_templates' => $composite_templates1,
'email_subject' => "Please sign the attached document",
'status' => "sent"
]);
try {
$config = new \DocuSign\eSign\Configuration();
$config->setHost(base_uri . 'restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . access_token);
$api_client = new \DocuSign\eSign\Client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
$result = $envelope_api->createEnvelope(account_id, $envelope_definition);
$envelope_id = $result->getEnvelopeId();
printf("\nEnvelope status: %s. Envelope ID: %s\n", $result->getStatus(), $result->getEnvelopeId());
return $envelope_id;
} catch (Exception $e) {
printf ("\n\nException from createEnvelope!\n%s", $e->getMessage());
if ($e instanceof DocuSign\eSign\Client\ApiException) {
printf ("\nAPI error information: \n%s", $e->getResponseBody());
}
return FALSE;
}
}
function recipientView ($envelope_id) {
$recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest([
'authentication_method' => "None",
'client_user_id' => "1000",
'email' => "signer_email#example.com",
'return_url' => "https://docusign.com",
'user_name' => "Signer's name"
]);
if (!$recipient_view_request || !$envelope_id) {return;}
try {
$config = new \DocuSign\eSign\Configuration();
$config->setHost(base_uri . 'restapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . access_token);
$api_client = new \DocuSign\eSign\Client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
$result = $envelope_api->createRecipientView(account_id, $envelope_id,
$recipient_view_request);
print ("\nCreate recipient view succeeded.");
printf ("Open the signing ceremony's long URL within 5 minutes: \n%s\n\n", $result->getUrl());
} catch (Exception $e) {
printf ("\n\nException from createRecipientView!\n%s", $e->getMessage());
if ($e instanceof DocuSign\eSign\Client\ApiException) {
printf ("\nAPI error information: \n%s", $e->getResponseBody());
}
}
}
# The mainline
$envelope_id = sendDocuSignEnvelope();
recipientView($envelope_id);
print("Done.\n");

Laravel resource collection - paginate - JSON response error

I want to do paging at the Laravel API. As a result, I want to get data and status code type.
Controller :
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return response()->json($data, 200);
}
PersonCollection Resource :
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
Output :
https://i.hizliresim.com/LvlBzj.png
[
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
]
But I want.
https://i.hizliresim.com/LvlBWo.png
{
"data": [
{
"id": 1,
"first_name": "Burak Ali",
"last_name": "Ildır",
"email": "burak#gmail.com",
"phone": "376.395.7233",
"city": "Koelpinstad",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/1"
}
},
{
"id": 2,
"first_name": "Vena",
"last_name": "Spinka",
"email": "shields.carolyn#example.org",
"phone": "716-268-7788 x092",
"city": "South Gudrunbury",
"href": {
"link": "http://127.0.0.1:8000/api/v2/person/2"
}
}
],
"links": {
"first": "http://127.0.0.1:8000/api/v1/person?page=1",
"last": "http://127.0.0.1:8000/api/v1/person?page=26",
"prev": null,
"next": "http://127.0.0.1:8000/api/v1/person?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 26,
"path": "http://127.0.0.1:8000/api/v1/person",
"per_page": 2,
"to": 2,
"total": 52
}
}
I want other page links. But when I convert it to JSON data, links and metadata do not come.
A resource collection describes how a collection of models will be transmitted as JSON.
You seem to be using it for an individual model. What you need is:
public function toArray($request)
{
return $this->collection->map(function ($person) {
return [
'id' => $person->id,
'first_name' => $person->first_name,
'last_name' => $person->last_name,
'email' => $person->email,
'phone' => $person->phone,
'city' => $person->city,
'href' => [
'link' => route('person.show', $person->id),
],
];
});
}
However the recommended way is to make a PersonResource instead in the same namespace and implement the toArray($request) in that class:
Person
class Person extends Resource //The name is important
{
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'phone' => $this->phone,
'city' => $this->city,
'href' => [
'link' => route('person.show', $this->id),
],
];
}
}
PersonCollection
class PersonCollection extends ResourceCollection
{
// This class is intentionally empty
}
Finally you should let Laravel handle how to make the response:
public function index()
{
$data = PersonCollection::collection(Person::paginate(2));
return $data->toResponse();
}
The default behaviour of the resource collection is to look for a resource which is named like the collection but with the Collection part removed (in this case PersonCollection will look for a Person resource).
This should ensure each model is converted according to the resource and the pagination behaviour is maintained.

How to validate request in json objects - using laravel

My json has two objects one is user_profile and other one is privileges but my validation is working only on user_profile object.
My json:
{
"user_profile": {
"email": "shahzad11#ovadamd.com",
"password": "admin123",
"password_confirmation": "admin123",
"status": 0,
"first_name": "Shahzad",
"middle_name": "Hussain",
"last_name": "Shah",
"date_of_birth": "2015-01-01",
"gender": "M",
"area_id": 1,
"address": "Minhatten NY",
"city": "New York",
"state": "Washington",
"zip": "12312",
"fax": "111-111-1111",
"phone_extension": "2471",
"work_phone": "111-111-1111",
"phone_no": "111-111-1111",
"emergency_contact": "111-111-1111",
"social_security": "111-11-1111",
"module_id": 2
},
"privileges": {
"is_super_admin": 1,
"facilities": [
{
"facility_id": 1,
"is_facility_supervisor": 0,
"speciality_id": 1,
"priv_id": "",
"role_id": 1
}
]
}
}
I want to validate my "privileges" object as well.
My controller:
public function register(Request $request) {
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
}
and my validateUser method:
public static function validateUser($data = [], $update = false) {
$rules = [
'first_name' => 'required|max:25',
'last_name' => 'required|max:25',
"address" => 'required|max:197',
"city" => 'required|max:20',
"zip" => 'required|max:5',
"phone_no" => 'required|max:12',
"area_id" => 'exists:areas,id',
"phone_extension" => 'min:3|max:5',
'gender' => 'in:M,F,X',
"work_phone" => 'max:12',
"emergency_contact" => 'max:12',
"fax" => "max:12",
"social_security" => 'required|max:11',
"module_id" => 'exists:modules,id',
// privileges object fields
"role_id" => 'required|exists:roles,id',
"facility_id" => 'required',
"speciality_id" => 'required'
];
if($update) {
$rules['id'] = 'required|exists:users,id';
} else {
$rules['email'] = 'required|email|unique:users';
$rules['password'] = 'required|min:6';
$rules['password_confirmation'] = 'required_with:password|min:6|same:password';
}
return $validator = Validator::make($data, $rules);
}
How i can put validation on privileges object?
Your help will be highly appreciated!
// privileges object fields
"facilities.*.role_id" => 'required|exists:roles,id',
"facilities.*.facility_id" => 'required',
"facilities.*.speciality_id" => 'required'
I think it will solve your problem
you can do this
Validator::make($request->all(),[
'your rules'])

Laravel get the sent data to the request

I am implementing an API using Laravel 5.4 . I want to send the title, description, time and user_id as a JSON and after that to get the JSON response with the input data.
Here is my code:
$title = $request->input('title');
$description = $request->input('description');
$time = $request->input('time');
$user_id = $request->input('user_id');
$meeting = [
'title' => $title,
'description' => $description,
'time' => $time,
'user_id' => $user_id,
'view_meeting' => [
'href' => 'api/v1/meeting/1',
'method' => 'GET1'
]
];
$response = [
'msg' => 'Meeting created',
'meeting' => $meeting
];
return response()->json($response, 201);
After running the server, I make a post request using POSTMAN (body->raw:)
{
"time": "201601301330CET",
"title": "Test meeting 2",
"description": "Test",
"user_id": 2
}
But it return this:
{
"msg": "Meeting created",
"meeting": {
"title": null,
"description": null,
"time": null,
"user_id": null,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}
Why the title, description, time and user_id fields are null?
You need to set Postman's content-type dropdown to JSON (application/json). Changing that setting changed the null values in the response to:
{
"msg": "Meeting created",
"meeting": {
"title": "Test meeting 2",
"description": "Test",
"time": "201601301330CET",
"user_id": 2,
"view_meeting": {
"href": "api/v1/meeting/1",
"method": "GET1"
}
}
}

Categories