Laravel: Edit value only if it appears in the request? - php

in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);

Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).

Related

Laravel: Factory Fake Car Data

I created a new factory in Laravel called "CarFactory.php" and I want to use https://github.com/pelmered/fake-car.
This is the fake data that I will insert into my database using Tinker:
return [
'name' => $this->faker->vehicleBrand(),
'founded' => $this->faker->biasedNumberBetween(1998,2017, 'sqrt'),
'description' => $this->faker->paragraph()
];
In the Laravel usage code, I'm not sure where to put this (e.g. Car Model, CarFactory):
$faker->addProvider(new \Faker\Provider\Fakecar($faker));
$v = $faker->vehicleArray();
return [
'vehicle_type' => 'car',
'vin' => $faker->vin,
'registration_no' => $faker->vehicleRegistration,
'type' => $faker->vehicleType,
'fuel' => $faker->vehicleFuelType,
'brand' => $v['brand'],
'model' => $v['model'],
'year' => $faker->biasedNumberBetween(1998,2017, 'sqrt'),
];
Help is needed to know how to set this up.

keep getting an error while saving data into database in laravel

I am using laravel ver "laravel/framework": "5.8.*"
I want to save the data into database with post request and my post data is
I have searched on this many topics but I can't get any information on this specific topic. If anyone can, it will be very helpful to me.
I saw my previous codes they this type of code in laravel but they work fine why this is not saving and getting an error.
{
"userID": 11,
"fullname": "dharmendra shah",
"fatherName": "manohar shah",
"Mothername": "manorama devi",
"dobdate": "21",
"dobmonth": "August",
"dobYear": "1999",
"caste": "OBC",
"casteCertificateIs": "state",
"emailAddress": "dharmonly1999#gmail.com",
"gender": "Male",
"handiCappedStatus": "Not handicapped",
"nationality": "india",
"state": "Rajasthan",
"district": "bikaner",
"tahsil": null,
"village": "NA",
"maritalStatus": "UnMarried",
"spouseName": null,
"children": null
}
In laravel route my controller is :
public function store(Request $request)
{
$this->validate($request, [
'fullname' => 'required|max:25',
'fatherName' => 'required|max:25',
'Mothername' => 'required|max:25',
'dobdate' => 'required',
'dobmonth' => 'required',
'dobmonth' => 'required',
'dobYear' => 'required',
'caste' => 'required',
'casteCertificateIs'=>'required',
'emailAddress' => 'required|email',
'gender' => 'required',
'handiCappedStatus' => 'required',
'nationality' => 'required',
'state' => 'required',
'district' => 'required',
'block' => 'sometimes|max:20',
'tahsil' => 'sometimes|max:20',
'village' => 'sometimes|max:20',
'maritalStatus' => 'required',
'spouseName' => 'sometimes|max:20',
'children' => 'sometimes|max:5|integer'
]);
$userInformationSave = new BauserInformation([
'userID' => \Auth::user()->id,
'fullname' => $request->get('fullname'),
'fatherName' => $request->get('fatherName'),
'Mothername' => $request->get('Mothername'),
'dobdate' => $request->get('dobdate'),
'dobmonth' => $request->get('dobmonth'),
'dobYear' => $request->get('dobYear'),
'caste' => $request->get('caste'),
'casteCertificateIs' => $request->get('casteCertificateIs'),
'emailAddress' => $request->get('emailAddress'),
'gender' => $request->get('gender'),
'handiCappedStatus' => $request->get('handiCappedStatus'),
'nationality' => $request->get('nationality'),
'state' => $request->get('state'),
'district' => $request->get('district'),
'block' => $request->get('block'),
'tahsil' => $request->get('tahsil'),
'village' => $request->get('village'),
'maritalStatus' => $request->get('maritalStatus'),
'spouseName' => $request->get('spouseName'),
'children' => $request->get('children')
]);
$userInformationSave->save();
return redirect()->route('home')->with('message', 'Your information is saved now');
}
The model is
class BauserInformation extends Model
{
protected $table = ['userFinalInformation'];
protected $fillable = ['userID', 'fullname', 'fatherName', 'Mothername', 'dobdate', 'dobmonth', 'dobYear', 'caste', 'casteCertificateIs', 'emailAddress', 'gender', 'handiCappedStatus', 'nationality', 'state', 'district', 'Block', 'tahsil', 'village', 'maritalStatus', 'spouseName', 'children'];
}
the error argument i am getting is
ErrorException (E_NOTICE)
Array to string conversion
You are complicating things.
On top of your controller put: use Illuminate\Support\Facades\Validator;.
Delete $userInformationSave.
Validate inputs:
$validator = Validator::make($request->all(), [
'fullname' => ['required', 'max:25'],
... every other input like I have done
]);
if ($validator->fails()) {
return redirect('/bla bla bla/create')->withErrors($validator);
}
And save the model:
BauserInformation::create($request->all());
EDIT #1
In you model, you should declare table and A_I like this:
protected $table = 'userFinalInformation';
protected $primaryKey = 'userID';
I think this will do the job.

Create Associative Array with Foreach, Insert into existing Associative Array

Hello.
I currently have a problem with the AWS Route-53 API. To create a record you need to call a function, which itself needs an array of inputs.
I want to create a record set here and for that I have some POST values. One of them, $_POST['record_value'], is a textarea and has multiple lines. I loop through them. This is to enable multiple values for one record. The code is as follows when you hardcode it as one value in ResourceRecords;
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
[
'Value' => $recordValue
],
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
Hower. I want to make ResourceRecords dynamically. For every line in the textarea I need a new set of the following part of the code;
[
'Value' => $recordValue
],
What I thought is the following;
$newData = [];
foreach(explode("\r\n", $recordValue) as $valLine) {
$newData[] = ["Value" => $valLine];
}
$result = $this->route53->changeResourceRecordSets([
'ChangeBatch' => [
'Changes' => [
[
'Action' => 'CREATE',
'ResourceRecordSet' => [
'Name' => $recordName,
'ResourceRecords' => [
$newData
],
'TTL' => $recordTtl,
'Type' => $recordType,
],
],
],
'Comment' => 'Routing Record Set',
],
'HostedZoneId' => $this->zone,
]);
However, this seems to return an exception: Found 1 error while validating the input provided for the ChangeResourceRecordSets operation:↵[ChangeBatch][Changes][0][ResourceRecordSet][ResourceRecords][0] must be an associative array. Found array(1).
Am I building the array wrong or am I doing this wrong alltogether?
$newData is already an array, you don't need to wrap it in another array.
'ResourceRecords' => $newData,

Custom error message in Laravel

I am validating an array in Laravel. I get "0.id has already been taken." in default error message. So I added a 2nd parameter in my validator: 'unique' =>':attribute has already been taken. Please fix your data in spreadsheet.' and shows "0.id has already been taken. Please fix your data in spreadsheet.". I added the 3rd parameter which is the custom attribute. ['*.id' =>'Student ID']. But I want to have a message like this: ID has already been taken. Please fix your data in spreadsheet in line 1.
Here's my full validation code:
$validate = $request - > validate([
'*.id' => 'required|unique:students|numeric',
'*.rfid_number' => 'required|unique:students|numeric',
'*.first_name' => 'required|alpha|max:100',
'*.middle_name' => 'alpha|max:100|nullable',
'*.last_name' => 'required|string|max:100',
'*.name_extension' => 'alpha|max:10|nullable',
'*.email' => 'required|email|unique:students',
'*.photo' => 'string|nullable',
'*.house_number' => 'required|integer',
'*.barangay' => 'required|alpha|max:100',
'*.city' => 'required|alpha|max:100',
'*.province' => 'required|string|max:100',
'*.zip_code' => 'required|integer',
'*.birth_date' => 'required|date|max:100',
'*.birth_place' => 'string|max:200',
'*.gender' => 'required|alpha',
'*.religion' => 'alpha|max:100|nullable',
'*.landline_number' => 'numeric|max:20|nullable',
'*.mobile_number' => 'required',
'*.father_name' => 'string|max:200|required',
'*.father_occupation' => 'string|max:200|nullable',
'*.mother_name' => 'string|max:200|required',
'*.mother_occupation' => 'string|max:200|nullable',
'*.guardian_name' => 'string|max:200|required',
'*.guardian_occupation' => 'string|max:200|nullable',
'*.guardian_address' => 'string|max:200|nullable',
'*.year' => 'integer|max:10|required',
'*.section' => 'alpha|max:200|required'
], [
'unique' => ':attribute has already been taken. Please fix your data in spreadsheet.'
], [ //attributes
'*.id' => 'Student ID'
]);
Something like this would do the trick:
$validate = $request->validate([
//
], [
//
],
collect($request->all())->keys()->flatMap(function ($index) {
return ["$index.id" => 'ID'];
})->toArray());
Iterate over all the indexes so you end up with something like:
[
'0.id' => 'ID',
'1.id' => 'ID',
'2.id' => 'ID',
'3.id' => 'ID',
'4.id' => 'ID',
'5.id' => 'ID',
'6.id' => 'ID',
'7.id' => 'ID',
]
As your final array to the validator

Braintree php back-end

I clone braintree project from https://github.com/braintree/braintree_php_example. Than I created account https://www.braintreepayments.com/sandbox. I must to return client_token. I debug this code
$result = Braintree\Transaction::sale([
'amount' => $amount,
'paymentMethodNonce' => $nonce,
'options' => [
'submitForSettlement' => true
]
]);
var_dump($result->transaction);
But token = null. Maybe my steps are incorrect?
////////////////////////////////
I did it!
I create user
$result = Braintree_Customer::create([
'firstName' => 'Mike',
'lastName' => 'Jones',
'company' => 'Jones Co.',
'email' => 'mike.jones#example.com',
'phone' => '281.330.8004',
'fax' => '419.555.1235',
'website' => 'http://example.com']);
Than I get customer_id
$result->customer->id;
Than I get token
$clientToken = Braintree_ClientToken::generate([
"customerId" => $result->customer->id
]);
Maybe problem with custom register in https://www.braintreepayments.com/sandbox.
Maybe I didn't put all information

Categories