Store an array of elements to database (Laravel) - php

I need advice how to store an array to database. For example i have an input with name="user_phone[]" and i want to store to database the value of this input.
I have a form like so, also there other inputs but i copy just one:
{!! Form::open([route('some.router')]) !!}
<fieldset class="form-group">
{{ Form::label(null, 'Phone') }}
{{ Form::text('user_phone[]', null, ['class' => 'form-control'] ) }}
</fieldset>
{!! Form::close() !!}
and the controller:
public function postAddOrder(Request $request)
{
$this->validate($request, [
'receipt_date' => 'date|required',
'return_date' => 'date|required',
'user_name' => 'required',
'user_phone' => 'required',
'work_sum' => 'integer|required',
'user_descr' => 'required',
'foruser_descr' => 'required'
]);
$user = new User;
$user = $user->all()->find($request->input('user_name'));
$order = new Order([
'receipt_date' => $request->input('receipt_date'),
'return_date' => $request->input('return_date'),
'user_name' => $user->fio,
'user_phone' => $request->input('user_phone'),
'device' => $request->input('device'),
'work_sum' => $request->input('work_sum'),
'master_name' => $request->input('master_name'),
'user_descr' => $request->input('user_descr'),
'foruser_descr' => $request->input('foruser_descr'),
'type' => $request->input('type'),
'status' => $request->input('status'),
'engineer' => $request->input('engineer'),
'partner' => $request->input('partner'),
'office' => $request->input('office')
]);
$order->save();
return redirect()->route('admin.orders.index');
}
The problem is when i'm submitting the form and getting the error:
htmlentities() expects parameter 1 to be string, array given
Also i'm using casts to store an array to DB:
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'user_phone' => 'array',
];
The values are storing correctly, the main problem is that the validate() method is not catching the errors. For example im not filling some data in inputs which are required. When instead of getting the error like something is required im getting error
htmlentities() expects parameter 1 to be string, array given
When im filling all input with data everything goes ok.

I think the problem comes from your rule
'user_phone' => 'required
To validate array values you should use the array validation. (Link)
rewrite your rule like so
"user_phone.0" => "required"
this will ensure that at least one user_phone is provided.
In case you wanna validate phone format just go with:
"user_phone.*" => "{Insert validation here}"

Found the definition.
{!! Form::open([route('some.router')]) !!}
<fieldset class="form-group">
{{ Form::label(null, 'Phone') }}
{{ Form::text('user_phone[0]', null, ['class' => 'form-control'] ) }}
</fieldset>
{!! Form::close() !!}
We must pass the index in inputs. Like name="user_phone[0]" after that we are not getting the error:
htmlentities() expects parameter 1 to be string, array given
And validate() method catching the errors. It was the only solution for me.

Related

How to have multiple products that depend on user input Laravel

I am using the srmklive/laravel-paypal package for my paypal API.
Currently, in my view I have multiple instances of this code block with varying product ids
{!! Form::open(['action' => 'PaypalController#expressCheckout']) !!}
{{ Form::hidden('item', 1) }}
{{ Form::hidden('name', 'm') }}
{{ Form::hidden('price', 25) }}
{{Form::submit('Pay via Paypal', array('class' => 'btn-info btn'))}}
{!! Form::close() !!}
However, when I use this method with my getCart function,
if($product == 1) {
return [
'items' => [
[
'name' => 'Mystery Core',
'price' => 25,
'qty' => 1,
],
],
'return_url' => url('/paypal/express-checkout-success'),
'invoice_id' => config('paypal.invoice_prefix') . '_' . $invoice_id,
'invoice_description' => "Order #" . $invoice_id . " Invoice",
'cancel_url' => url('/'),
'total' => 25,
];
}
}
the variables return null since they're coming from paypal's end, giving me a null error.
"Trying to access array offset on value of type null"
How can I go about having multiple products? I have heard of the addOptions function but I cannot understand it.
Even a different package suggestion is welcome!

Laravel - Select input not keeping old value

I have a piece of code:
{!! Form::select('option_employee_review', old('option_employee_review', $employeeReviews), $employeeReviews, ['id' => 'option_employee_review', 'class' => 'form-control ']); !!}
It saves the value to the database correct. When i go to edit the item again the select input does not keep the old value that's in the database. How do i make it so that the select input does keep its old value.
$employeeReviews:
[
2843 => "Medewerker review 1"
2849 => "Medewerker review 2"
]
I am not using your syntax, but something like this will do I think.
<option value="{{$channel->id}}" {{ (old("channel_id") == $channel->id ? "selected" : "" ) }}>{{$channel->title}}</option>
Second parameter to select function must be array of options.
Try changing it like this
{!! Form::select('option_employee_review', $employeeReviews, old('option_employee_review', $employeeReviews), ['id' => 'option_employee_review', 'class' => 'form-control ']); !!}
Or based on your parent object let's say employee you can try
{!! Form::select('option_employee_review', $employeeReviews, $employee->option_employee_review, ['id' => 'option_employee_review', 'class' => 'form-control ']); !!}

"General error: 1366 Incorrect integer value" even though I have set validation to nullable

I get this error:
When I am trying to create and I am not filling the input for fixed_quantity
This is my store in my Controller(I have set fixed_quantity to nullable so it should be fine right?):
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'fixed_quantity' => 'nullable',
'max_increments' => 'required|numeric|min:0',
]);
DB::transaction(function () use ($request, $store, $variant) {
$subscription_plan = new SubscriptionPlan([
'store_id' => $store->uuid,
'variant_id' => $variant->uuid,
'name' => $request->input('name'),
'description' => $request->input('description'),
'max_increments' => $request->input('max_increments'),
]);
$subscription_plan->fixed_quantity = $request->input('fixed_quantity');
$subscription_plan->save();
This is what is on my blade:
<div class="form-group">
<label for="fixed_quantity">Quantity</label>
<input class="form-control" type="number" id="fixed_quantity" name="fixed_quantity" value="{{ old('fixed_quantity') }}"" placeholder="0">
</div>
If you look closely, the error is saying that it's trying to put '' in the column.
Check if the input is empty and don't set it if it is.
if (!empty($request->input('fixed_quantity')))
$subscription_plan->fixed_quantity = $request->input('fixed_quantity');
try this
check fixed_quantity before insert
'fixed_quantity' => $request->has('fixed_quantity') ? $request->input('fixed_quantity') : NULL,
this nullable store as string on integer field thats why
'fixed_quantity' => 'nullable',
nullable means that null is an acceptable value, but you are passing it an empty string (''), which is not. Change your code to something like this:
$subscription_plan->fixed_quantity = !empty($request->input('fixed_quantity')) ? $request->input('fixed_quantity') : null;

Laravel - htmlentities() expects parameter 1 to be string, array given

My blade.php code is:
{!! Form::input('text', 'tactic[]', null, array('id' => 'tactic', 'class' => ' form-control TabOnEnter', 'placeholder' => 'Tactics_1')) !!}
HtmlBuilder.php code is
public function escapeAll($value)
{
return htmlentities($value, ENT_QUOTES, 'UTF-8');
}
The error message is:
ErrorException in HtmlBuilder.php line 65:
htmlentities() expects parameter 1 to be string, array given (View: /home/seyali-02/dev/htdocs/scam/resources/views/dashboard/Scam/edit.blade.php)
And i have changed the blade.php as like
{!! Form::input('text','', 'tactic[]', null, array('id' => 'tactic', 'class' => ' form-control TabOnEnter', 'placeholder' => 'Tactics_1')) !!}
and
{!! Form::text('name', 'tactic[]', null, array('id' => 'tactic', 'class' => ' form-control TabOnEnter', 'placeholder' => 'Tactics_1')) !!}
and also text('text', .. But nothing works for me and throwing me the same error as i mentioned above.. I have gone through all the similar questions related to this but none of those answers solved my problem . So please avoid doing duplication of this question and give me clear and correct solution..
You are adding tactic[] to the name which is an array and hence when you post the data it is going as an array. Either remove it or at php end use implode.
If you want to take the input as an array then you can use this code
{!! Form::text('tactic[]',null,['id' => 'tactic', 'class' => ' form-control TabOnEnter', 'placeholder' => 'Tactics_1']) !!}

How to set custom data-attribute to option with Laravel Collective

I have a form, inside I have a select with some options and I'm using Laravel Collective Forms to build it, I have something like:
{!! Form::select('size', $data, $selecteds, ['multiple' => true]) !!}
All going well until here, but now I need to set a data-section attribute to each option, how can I make it?
I had to do the same thing recently. After inspecting the FormBuilder class to write my own marco I found out that the select() method actually has an undocumented fifth parameter for option attributes:
Form::select('size', $data, $selecteds, ['multiple' => true], $optionAttributes)
The index must match the value of the option, e.g.:
$optionAttributes = [
'S' => [
'data-title' => 'Small',
'data-surcharge' => '0',
],
'M' => [
'data-title' => 'Medium',
'data-surcharge' => '5',
],
'L' => [
'data-title' => 'Large',
'data-surcharge' => '10',
],
];
So I ended up writing a marco which generates this array based on a collection and then uses the default select() method. Something like that:
\Form::macro('locationSelect', function ($name, $value = null, $attributes = []) {
// Get all locations from the DB
$locations = \App\Location::all();
// Make an id=>title Array for the <option>s
$list = $locations->pluck('title', 'id')->toArray();
// Generate all data-attributes per option
$optionAttributes = [];
foreach ($locations as $location) {
$optionAttributes[$location->id] = [
'data-icon' => $location->icon,
'data-something' => $location->some_attribute,
];
}
// Use default select() method of the FormBuilder
return $this->select($name, $list, $value, $attributes, $optionAttributes);
});
Very convenient.
{{ Form::locationSelect('location_id') }}
You can pass option attributes as fifth parameter (version 5.8) like this
$optionParameters = collect($optionsArray)->mapWithKeys(function ($item) {
return [$item[id] => ['data-anything' => $item['anything']]];
})->all();
And select will look like
{!! Form::select('name', $optionsArray, null, ['class' => 'form-control', 'placeholder' => 'Select'], $optionParameters) !!}
I think it is much simpler and cleaner than creating macroses
Add it to a 4th argument which is an array:
{!! Form::select('size', $data, $selecteds, ['data-attribute' => 'John Smith', 'multiple' => true]) !!}

Categories