How to insert multiple form in laravel 5.4 - php

I have problem with input multiple form, in my case, result array is like this
{
approval_activities": null,
"remark_id": [
"9",
"10"
],
"name_remark": [
"Capex",
"Asset"
],
"label_remark": [
"Capex",
"Asset"
],
"description_remark": [
"Capex",
"Asset"
],
"filter_logic_remark": [
null,
null
],
"default_remark": [
"Capex",
"Asset"
],
"weight_remark": [
"5",
"1"
]
I try to insert it to other table using foreach, but I have error message Array to string conversion
$asset = Asset::create([,'approval_activities' => $request->approval_activities]);
$arr[] = $request->all();
foreach ($arras $req) { //remark
$i = 0;
$pret = [
'asset_id' => $asset->id,
'remark_id' => $req[$i]['remark_id'],
'name' => $req[$i]['name_remark'],
'label' => $req[$i]['label_remark'],
'description' => $req[$i]['description_remark'],
'filter_logic' => $req[$i]['filter_logic_remark'],
'default' => $req[$i]['weight_remark']
];
$i++;
}
RemarkAsset::create($pret);
this is my form in blade, in this code I use [] in name for send an array to controller, the result from this code is like JSON above.
{!! Form::label('approval_activities', 'Approval Jenis Kegiatan', ['class' => 'col-sm-2 control-label']) !!}
<div class="col-sm-4 {{ $errors->has('approval_activities') ? 'has-error' : ''}}">
<select id="approval_activities" name="approval_activities" class="form-control select2_demo_1"
data-placeholder="Select Approval Jenis Kegiatan">
<option value="">Select Approval Jenis Kegiatan</option>
<option value="Aktivasi">Aktivasi</option>
</select> {!! $errors->first('approval_kegiatan', '<p class="help-block">:message</p>') !!}
</div>
<div class="form-group">
{!! Form::label('name', 'Name', ['class' => 'col-sm-2 control-label']) !!}
<div class="col-sm-4 col-xs-12 {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::text('name_remark[]', $item->name, ['class' => 'form-control','placeholder'=>'Name']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
{!! Form::label('label', 'Label', ['class' => 'col-sm-2 control-label f-w-none']) !!}
<div class="col-sm-4 col-xs-12 {{ $errors->has('label') ? 'has-error' : ''}}">
{!! Form::text('label_remark[]', $item->name, ['class' => 'form-control','placeholder'=>'Label']) !!}
{!! $errors->first('label', '<p class="help-block">:message</p>') !!}
</div>
</div>
My expect is inserting $asset to table asset just have 1 record, and the remark is inserted to table remark, if I have two remark_id or other like JSON above then the record in table remark is two.

The $req[$i]['name_remark'] would work if the array looked like the following, where there is a name_remark for every $i.
{
"name_remark": "Capex"
},
{
"name_remark": "Asset"
}
In your case I believe you want $req['name_remark'][$i] instead.

Related

How do I save multiple objects to a JSON column in MySQL and Laravel

I am using Laravel 5.4 and I have a problem in that when I save out a group of checkboxes, it only saves one of them if I save it like this:
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[name]', 'Spanish') !!} Spanish</label><br/>
But it gives me a workable format in that I can run searches on name. The output here is just the first one I checked but in this format:
{"name": "English"}
If I take out the array field name in the [].
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[]', 'Spanish') !!} Spanish</label><br/>
It saves all the values but it doesnt give me a workable format for my searches etc. The output here is:
["English", "French"]
My function in Laravel is like this
public function store(Request $request)
{
$data = $request;
dd($data['languages']);
$resource = Resource::create([
'user_id' => auth()->id(),
'status_id' => $status,
'title' => $data['title'],
'languages' => $data['languages'],
]);
return redirect($resource->path());
}
The column in MySQL called 'languages' is a JSON type.
Now ideally, I would like to get something similar to {"name": "English"} but not just saving as one item but all of them.
Any suggestions?
You can do the following:
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'English') !!} English</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'French') !!} French</label><br/>
<label class="checkbox-inline"> {!! Form::checkbox('languages[][name]', 'Spanish') !!} Spanish</label><br/>
It will give you:
"languages" => array [
0 => array: [
"name" => "English"
],
1 => array: [
"name" => "French"
],
2 => array: [
"name" => "Spanish"
]
]

Insert Cart::content() into multiple Row From View Using Eloquent Laravel 5

How can I insert Multiple Row of Cart:: content() in Laravel 5.
I'm using Crinsane/LaravelShoppingcart for my cart, however, when you click on proceed to payment, I want the user to fill Customer details like (Terminal ID, sale date, and customer name. But I'm having issue with inserting Cart::(Content) into my database (I dont want to insert instance. I like to break the cart down to my database column. example, if someone pick like 2-5 items, I want it to be inserted to my db, with each item in each row. I've break the Cart::content down in my view, but I need to be able to use Laravel to insert multiple row based on the number of Items selected.
PLEASE NOTE: IF I ONLY ADD ONLY ONE ITEM TO CART, I'M ABLE TO INSERT TO DATABASE, IT'S ONLY WHEN THE ITEM IN CART IS MORE THAN ONE THAT I HAVE ISSUE WITH.
Below is my proceed.blade.php
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label('product_name', 'Product Name:') !!}
{!! Form::text('product_name', $item->name, ['class'=>'form-control'])!!} </div>
<div class="form-group">
{!! Form::label('quantity', 'Quantity:') !!}
{!! Form::text('quantity', $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('unit_price', 'Unit Price:') !!}
{!! Form::text('unit_price', $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('rowId', 'Row ID:') !!}
{!! Form::text('rowId', $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('tax', 'Tax:') !!}
{!! Form::text('tax', $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('total_price', 'Sub Total:') !!}
{!! Form::text('total_price', $item->subtotal, ['class'=>'form-control'])!!}
</div>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
`
MY CONTROLLER
$counter= $request['counter'];
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request['terminal_id'],
'customer_name' => $request['customer_name'],
'unit_price' => $request['unit_price'],
'total_price' => $request['total_price'],
'tax' => $request['tax'],
'quantity' => $request['quantity'],
'product_name' => $request['product_name'],
'sale_date' => $request['sale_date'],
'rowId' => $request['rowId']
]);
}
return redirect('shop');
}
First your fields are not arrays so with each #foreach in your view, the old value overrides.
Make your inputs to Array inputs by changing your view this way:
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
<?php $idx = 0; ?>
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label("product_name[$idx]", 'Product Name:') !!}
{!! Form::text("product_name[$idx]", $item->name, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("quantity[$idx]", 'Quantity:') !!}
{!! Form::text("quantity[$idx]", $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("unit_price[idx]", 'Unit Price:') !!}
{!! Form::text("unit_price[idx]", $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("rowId[$idx]", 'Row ID:') !!}
{!! Form::text("rowId[$idx]", $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("tax[$idx]", 'Tax:') !!}
{!! Form::text("tax[$idx]", $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("total_price[$idx]", 'Sub Total:') !!}
{!! Form::text("total_price[$idx]", $item->subtotal, ['class'=>'form-control'])!!}
</div>
<?php $idx++; ?>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I suggest you also putting your for loop in a transaction in order to improve it's safety.
Like this:
public function store(SalesCreateRequest $request) {
$counter = Input::get('counter');
\DB::transaction(function() use ($counter){
for ($i=0; $i < $counter; $i++){
Sale::create([
'terminal_id' => Input::get("terminal_id")[$i],
'customer_name'=> Input::get("customer_name")[$i],
'unit_price'=> Input::get("unit_price")[$i],
'total_price'=> Input::get("total_price")[$i],
'tax'=> Input::get("tax")[$i],
'quantity'=> Input::get("quantity")[$i],
'product_name'=> Input::get("product_name")[$i],
'sale_date'=> Input::get("sale_date")[$i],
'rowId'=> Input::get("rowId")[$i]
]);
}
});
return "working";
}
Note that you could simply add a [] suffix instead of [$idx] in your input names to make your inputs arrays, but usually indexing your inputs explicitly is safer.
Edit the $idx key from Cart::content() was returning a weird number, that was why simple numerical numbers threw Out of range exception.
Change your view code as I did above, I hope fixing it this way.
Hope it helps
Just modify your controller
$counter = $request['counter'];
\DB::transaction(function() use ($counter, $request) {
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request["terminal_id"],
'customer_name' => $request["customer_name"],
'unit_price' => $request["unit_price"][$i],
'total_price' => $request["total_price"][$i],
'tax' => $request["tax"][$i],
'quantity' => $request["quantity"][$i],
'product_name' => $request["product_name"][$i],
'sale_date' => $request["sale_date"],
'rowId' => $request["rowId"][$i]
]);
}
});
NOTE
Not all input fields are array (terminal_id, sale_date...)

phalcon form add options

I have a problem with phalcon form. I added a form but i can not add options like
[
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]
I want to add all of them which called setuserOption in phalcon document but I can't do that.
//form add user options
$this->setuserOptions(
[
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]
);
//my form
$this->setuserOptions([
'id' => 'login-form',
'class' => 'form form-x',
'data-form-style' => 'dynamic, rootable, hash',
'data-encrypt' => 'false'
]);
}
//this is volt ( form.options is written by me .how can i use this options )
{{ content() }}
{{ form('login/login', form.options) }}
<div class="form-group">
{{ form.label('username') }}
{{ form.render('username', ['class': 'form-control']) }}
</div>
<div class="form-group">
{{ form.label('password') }}
{{ form.render('password', ['class': 'form-control']) }}
</div>
<div class="form-group">
{{ form.render('submit', ['class': 'btn btn-primary btn-large']) }}
</div>
</form>
If you look at the documentation, you can add properties to your form tag like this:
<?php
echo Phalcon\Tag::form(array("posts/save", "method" => "post"));
or with the Volt syntax:
<?php
{{ form("posts/save", "method": "post") }}

Laravel inserting "null" into database from form input.

This is a strange problem i've run into. I have a form that takes in First, Last, Title, Email, and Phone which takes that data and inputs into a ContactPerson table I have set up in a database.
When I fill out the form, and hit submit, only the Title, Email, and Phone number get inserted correctly into the database. The first and last names get inserted as NULL.
Here's some of my code that I have using PHPstorm and Laravel 2.5.3
My Create a New Contact view:
<h1 style="text-align:center;">Add A New Contact Person</h1>
<hr/>
{!! Form::open(['url' => '/create']) !!}
<span style="text-align:center;align-content:right;display:block; margin-right:auto;margin-left:auto;">
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('title', 'Title: ') !!}
{!! Form::text('Title', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('email', 'Email: ') !!}
{!! Form::text('Email', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('phone', 'Phone: ') !!}
{!! Form::text('Phone', null, ['class' => 'form']) !!}
</div>
{!! Form::submit('Submit', ['class' => 'btn btn-primary form']) !!}
</span>
{!! Form::close() !!}
Here is my controller called ResourceController I have created:
class ResourceController extends Controller
{
public function resource()
{
$contacts = ContactPerson::all();
return view('pages.resource', compact('contacts'));
}
public function create()
{
return view('pages.create');
}
public function store(Requests\CreateNewContactRequest $request)
{
ContactPerson::create($request->all());
return redirect('resource');
}
}
Here's the validation I have set up in the CreateNewContactRequest class for the form:
public function rules()
{
return [
'First' => 'required|min:2',
'Last' => 'required|min:1',
'Title' => 'required|min:2',
'Email' => 'required|Email|unique:users',
'Phone' => 'required|numeric|min:9'
];
}
Here's what it looks like when I fill out/submit the form.
After hitting submit it redirects to the database dump:
the view of the database after insertion:
Looking at your dump details, your field names need to match your form names or visa versa, so your form names need to change to say:
<div class="form">
{!! Form::label('first', 'First Name: ') !!}
{!! Form::text('First_Name', null, ['class' => 'form']) !!}
</div>
<div class="form">
{!! Form::label('last', 'Last Name: ') !!}
{!! Form::text('Last_Name', null, ['class' => 'form']) !!}
</div>
EG for field name First_Name your input needs to be named the same name="First_Name"
Also making sure your fillable details are also correct
protected $fillable = ['First_Name','Last_Name','Title','Email','Phone'];

How can I make a search that is filtered by multiple inputs in Laravel 4.2?

I want this form to search multiple fields. How can I aggregate these search terms and filter them by their appropriate fields?
For example, if the user types "Book" into the textsearch field, and then selects "Assigned" from the status dropdown, the page should return all requests containing 'book' in the subject or details field, and 'assigned' in the status field.
I have the following form in my Laravel 4.2 Application:
{{ Form::open(['route' => 'requests.search']) }}
<!-- Text Search Form Input -->
<div class="form-group">
{{ Form::label('textsearch', 'Text Search:') }}
{{ Form::text('textsearch', $query, ['class' => 'form-control']) }}
{{ Form::hidden('search', 'text') }}
</div>
<!-- Status Form Input -->
<div class="form-group">
{{ Form::label('status', 'Status:') }}
{{ Form::select('status', $statuses, null, ['class' => 'form-control']) }}
</div>
<!-- Category Form Input -->
<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', $categories, null, ['class' => 'form-control']) }}
</div>
<!-- Teamleader Form Input -->
<div class="form-group">
{{ Form::label('teamleader', 'Team Leader:') }}
{{ Form::select('teamleader', $projectmembers, null, ['class' => 'form-control']) }}
</div>
<!-- Requestid Form Input -->
<div class="form-group">
{{ Form::label('requestid', 'Request ID:') }}<br/>
<span>Between:</span>
{{ Form::text('requestidstart', null, ['class' => 'form-control', 'style' => 'width:100%;']) }}
<span>And:</span>
{{ Form::text('requestidend', null, ['class' => 'form-control', 'style' => 'width:100%;'])}}
</div>
<!-- Requestdate Form Input -->
<div class="form-group">
{{ Form::label('requestdate', 'Request Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestdatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestdateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
<!-- Requestduedate Form Input -->
<div class="form-group">
{{ Form::label('requestduedate', 'Due Date:') }}<br/>
<span>From:</span>
{{ Form::text('requestduedatestart', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;']) }}
<span>To:</span>
{{ Form::text('requestduedateend', null, ['class' => 'form-control etadatepicker', 'style' => 'width:100%;'])}}
</div>
{{ Form::submit('Search') }}
{{ Form::close() }}<br/>
Controller:
$requestresponsetype = ['' => ''] + RequestResponseType::lists('description', 'description');
$projectmembers = ['' => ''] + RequestProjectMember::lists('first_name', 'first_name');
$statuses = ['' => ''] + RequestStatus::lists('description', 'description');
$categories = ['' => ''] + RequestCategory::lists('description', 'description');
$query = Input::get('textsearch');
$requests = DataRequest::where("subject", "LIKE", "%$query%")->orWhere("details", "LIKE", "%$query%")->orWhere("id","LIKE","%$query%")->paginate(10);
return View::make('requests.index', ['requests' => $requests, 'statuses' => $statuses, 'requestresponsetype' => $requestresponsetype, 'projectmembers' => $projectmembers, 'categories' => $categories, 'query' => $query]);
I don't understand your idea clearly, but I guess something like:
$requests = DataRequest::where(function($q) {
$q->where("subject", "LIKE", "%$query%")
->orWhere("details", "LIKE", "%$query%")
->orWhere("id","LIKE","%$query%");
})
->where('status', '=', $status)
->paginate(10);
In my project, I created a scope to search, it's reuseable and readable.
//BaseModel
public function scopeSearch($query, $search, $fields)
{
$query->where(function($q) use ($search, $fields) {
foreach ($fields as $field) {
$q->orWhere($field, "LIKE", "%$search%");
}
}
}
$requests = DataRequest::search($query, ["subject", "details", "id"])
->where('status', '=', $status)
->paginate(10);

Categories