Send array data from laravel view to controller - arrays

i'm trying to send an array from my laravel view to my controller, but i'm only receiving one part os the data, this is what i have:
<form
method="POST"
action="{{ url('/forms/reports') }}"
>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach ($results as $result)
<input value="{{ $result->code }}" name="code">
<input value="{{$result->name}}" name="name">
<input value="{{$result->user}}" name="user">
<input value="{{$result->number}}" name="number">
#endforeach
<div class="col-xs-9">
</div>
<div class="col-xs-3 container-download">
<button type="submit" class="btn btn-download" id="btn-download" >Download</button>
</div>
</form>
But results has this:
array (
0 => '1',
1 => 'Test Name 1',
2 => 'user1',
3 => '1',
), array (
0 => '2',
1 => 'Test Name 2',
2 => 'user2',
3 => '2',
);
And on the table that i have on my view is showing correctly, the two rows of data.
But when i do the post to receive on my controller the full results array, i only get the second row, when i print it like this:
public function generateExcel(Request $request)
{
$code = $request->input('code');
$name = $request->input('name');
$user = $request->input('user');
$number = $request->input('number');
$users = [$code, $name, $user, $number];
Log::debug($users);
}
And my Log shows me this:
[2020-12-30 12:43:58] local.DEBUG: array (
0 => '2',
1 => 'Test Name 2',
2 => 'user2',
3 => '2',
)
And i don't know if i should push the values first or i'm making another mistake. Can anyone help me with this?

That is happening because you are not sending an array. You will need to do something like this.
#foreach ($results as $result)
<input value="{{ $result->code }}" name="code[]">
<input value="{{$result->name}}" name="name[]">
<input value="{{$result->user}}" name="user[]">
<input value="{{$result->number}}" name="number[]">
#endforeach

Related

How do I instert multiple array into mysql using laravel

I want to insert data from my form into mysql bu I am getting errors. How do I solve this problem.
#foreach($assignments as $item)
<input type="text" name="class[]" value="{{$item->class}}" id="">
<input type="text" name="year[]" value="{{$item->year}}" id="">
<input type="text" name="subject_id[]" value="{{$item->subject_id}}" id="">
<label for="" class="ml-3 mt-2 mb-1">Score</label>
<input type="text" name="score[]" id="" style="width: 20rem;" class="form-control ml-3">
</div>
$class = $request->get("class");
$year = $request->get("year");
$subject_id = $request->get("subject_id");
foreach ($request->get('score') as $key => $value){
SubmitScores::create([
'class' => $key[$class],
'year' => $key[$year],
'subject_id' => $key[$subject_id]
]);
}
#endforeach
The error am getting is:
Trying to access array offset on value of type int
These are backwards:
$key[$class]
$key[$year]
$key[$subject_id]
Those should be $variable[$key]. $key is an integer index, like 0, 1, 2, and $class, $year and $subject_id ($variable) are arrays. So:
foreach ($request->get('score') as $key => $value){
SubmitScores::create([
'class' => $class[$key],
'year' => $year[$key],
'subject_id' => $subject_id[$key]
]);
}

Trying to get property 'price' of non-object in laravel

There's so many question about this but because I'm a newbie, I don't get it at all. so I've successfully saving multiple data into my db. I have 2 tables, TicketPrice as a list of price that visitor would choose, then I will save the selected data into Payment table. This is what I've done in my controller:
$idcategory = $request->id_category;
$price = $request->price;
$qty = $request->qty;
$data = [];
$i = 0;
foreach($idcategory as $key => $value) {
if ($qty[$i] > 0) {
for ($k=0; $k < $qty[$i] ; $k++) {
$data[] = [
"id_category" => $value,
"name" => $request->nama[$key],
"price" => $request->price[$key],
"qty" => $request->qty[$key],
];
}
}
$i++;
}
Payment::insert($data);
$latest = News::orderBy('date', 'DESC')->take(3)->get();
return view('form.conference-regist',compact('latest'))->with('data',$data);
and this is when I try to foreach the selected data (it's multiselect) in my blade after saving it on Payment table:
<?php foreach ($data as $key): ?>
<div class="row">
<div class="col-lg-12 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Price</label>
<input type="text" class="form-control" id="price" aria-describedby="emailHelp" name="price" value="{{$key->price}}">
</div>
</div>
</div>
<?php endforeach; ?>
I wonder if it necessary to put hasMany or belongsTo into the models? Or is there any easier way to solved it?
Well you can try this to get the inserted data back and to pass it to view
$data2 = Payment::insert($data);
$data2 = $data2->fresh(); //this will re-retrieve the inserted data back from table.
$latest = News::orderBy('date', 'DESC')->take(3)->get();
return view('form.conference-regist',compact('latest'))->with('data',$data2);

How to save multiple select in database?

I have a multi-select option and i want to save all record in database, now it's saving only the last one, how can I do that? I need to save multi-select from tags with comma (,) between. .
Here is my controller and what I tried
$news = News::create([
'locale' => Session::get('admin_locale'),
'title' => $request['title'],
'slug' => Slugify::slugify($request['title']),
'news_class' => $request['news_class'],
'description' => $request['description'],
'tag' => $request['tag'],
'tags' => $request->input['tags'],
'category' => 'news',
'category_id' => $request['category_id'],
'metatitle' => $request['title'],
'metadescription' => substr(strip_tags($request['description']), 0, 160),
'image' => $image,
]);
Here is my view:
<div class="row d-flex justify-content-center mt-100 col-md-12 g-mb-30" >
<div class="col-md-12" >
<label class="g-mb-10">Tags</label>
<select id="choices-multiple-remove-button" placeholder="Select" multiple title="Category Talent" name="tags">
#foreach($news as $tag)
<option value="{{ $tag->tag }}">{{ $tag->tag }}</option>
#endforeach
</select> </div>
</div>
To pass multiple values you probably want to rename your input to be an array:
<select ... name="tags[]">
Then on the server side you should receive them as an array under the input tags:
$tags = $request->input('tags', []);
You can join the array elements with implode to get a string representation:
$tags = implode(',', $tags);
PHP Manual - Function Reference - Text Processing - Strings - Functions - implode
$news = News::create([
...
'tags' => implode(',', $request->input('tags', [])),
...
]);

AngularJS http action executes multiple foreign event

I made a simple function to handle update actions for user. A simple form that look like this
<div class="com-md-12 col-sm-12 no-pad no-margine" ng-controller="ProfileCtrl" ng-init="getProfile('{{$safeID}}')">
{!! Form::open(array('class' => 'form-horizontal signup-form', 'ng-submit' => 'updateProfile($event)')) !!}
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('first_name', old('first_name'), array('class' => 'form-control', 'placeholder' => 'First Name*', 'ng-model' => 'uProfile.first_name')); !!}
{!! MessagerService::setInlineError($errors->first('first_name')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::text('last_name', old('last_name'), array('class' => 'form-control', 'placeholder' => 'Last Name*', 'ng-model' => 'uProfile.last_name')); !!}
{!! MessagerService::setInlineError($errors->first('last_name')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
{!! Form::text('username', old('username'), array('class' => 'form-control', 'placeholder' => 'Screen Name*', 'ng-model' => 'uProfile.username')); !!}
{!! MessagerService::setInlineError($errors->first('username')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6">
{!! Form::text('dob', old('dob'), array('class' => 'form-control', 'id' => 'dob', 'placeholder' => 'Date of Birth*', 'ng-model' => 'uProfile.dob')); !!}
{!! MessagerService::setInlineError($errors->first('dob')) !!}
</div>
<div class="col-md-6 col-sm-6">
{!! Form::select('gender', ['' => '------ Gender ------', 'male' => 'Male', 'female' => 'Female'], old('gender'),
array('class' => 'form-control', 'ng-model' => 'uProfile.gender')) !!}
{!! MessagerService::setInlineError($errors->first('gender')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<div class="input-group">
<span class="input-group-addon" id="p_url_pretext">example.com/</span>
{!! Form::text('profile_url', old('profile_url'), array('class' => 'form-control', 'placeholder' => 'Profile URL*', 'ng-model' => 'uProfile.profile_url')); !!}
</div>
{!! MessagerService::setInlineError($errors->first('profile_url')) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-sm-12">
<button type="submit" class="btn btn-default cbtn-login" style="float: right;">Save updates</button>
</div>
</div>
{!! Form::close() !!}
</div>
with angular script that look like this
$scope.updateProfile = function(event){
event.preventDefault();
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : $.param($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
};
Everything worked as i expected but I have noticed 1 weird behavior. Why are there so many unrecognized requests before my final POST action is being executed?
I noticed that supposed my action route is http://www.example.com:8000/ws/profile/update it somehow keeps on calling http://www.example.com:8000/ws/profile with 3 different requests POST, GET, and DELETE before it finally reaches the intended request as shown in image below
Anyone have any idea what causes such behavior to happen or have I coded something wrong in anywhere that leads to such incident?
Update 1: Here is the Plunkr file. Noted that i could not re-simulate the error because the site is currently at localhost
Update 2: I have narrowed down that the ng-init="getProfile('{{$safeID}}') might have been causing this problem. I tried removing that line and give it a constant value and the errors do not appear. What's with such behavior?
I have found out the problem that causes such behavior. It is mainly because of the jQuery's $.param function. What really happens is the $.param operation will run through all properties of you object. Using $.param as the object will not automatically convert to a url encoded string (though I think it should).
So what I as a workaround to this problem is create a manual serialization function like such
function serializeData( data ) {
// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) + "=" + encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer.join( "&" ).replace( /%20/g, "+" );
return( source );
}
pass the form payload to the serialization function then append it into angular's #http
$http({
method : 'POST',
url : svrid('www') + '/ws/profile/update',
data : serializeData($scope.uProfile), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
$scope.uError = null;
}).error(function(data) {
$scope.uError = data;
console.log(data);
});
and everything works like a charm.

Set the options for the Field of Type Radio button in Form Helper in Cakephp

I am using a Form helper in CakePHP. like
echo $form->input('field', array(
'type' => 'radio','legend'=>$r['Attribute']['label'],
// 'after' => '--after--',
// 'between' => '--between---',
'separator' => '--separator--',
'options' => array('1', '2')
));
which generates me as
<div class="input radio">
<fieldset>
<legend>Gender</legend>
<input type="hidden" value="" id="field_" name="data[field]"/>
<input type="radio" value="0" id="Field0" name="data[field]"/>
<label for="Field0">1</label>--separator--
<input type="radio" value="1" id="Field1" name="data[field]"/>
<label for="Field1">2</label>
</fieldset>
</div>
Is there any way to keep my options that i have received from my Database instead of 1,2
where i tried it with receving my options using
<?php foreach ($viewfields as $r): ?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
$("#"+<?=$r['Attribute']['id'];?>).each(function() {
type= "<?=$r['Attribute']['type'];?>";
if(type=="radio")
{
var ht = $.ajax({
type: "GET",
url: "http://localhost/FormBuilder/index.php/forms/viewChoices/"+attribute_id,
async: false
}).responseText;
var myObject = eval('(' + ht + ')');
var data = myObject;var j=0;
$.map(data.choices, function(i){ j++;
alert(i.choice);//which alerts as male and female correctly.
return i.choice;});
}
});//each
});
alert(i.choice); alerts the options correctly ..
How to keep these options in the array() of the Form Helper so that to get these options male and female instead of default 1,2
Please suggest me..
Place the options in a key => value array - as shown here : Cake Options
echo $form->input('field', array(
'type' => 'radio',
'legend' => $r['Attribute']['label'],
'separator' => '--separator--',
'options' => array('Male' => 'male', 'Female' => 'female')
));
See how you go.

Resources