Laravel insert records (foreign key) - laravel

When I trying add new record to database Laravel returned error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(kurwa_magazyn.transmits, CONSTRAINT
transmits_to_user_id_foreign FOREIGN KEY (to_user_id) REFERENCES
users (id)) (SQL: insert into transmits (from_user_id,
to_user_id, product_id, quantity, transmit, created_at,
updated_at, user_id) values (1, 0, 1, 3, 0, 2016-08-16 18:08:53,
2016-08-16 18:08:53, 1))
$transmit = new transmit($request->all());
$transmit['from_user_id'] = $idKey;
$transmit['to_user_id'] = $idKey2;
$transmit['product_id'] = $downloadProductsId;
$transmit['quantity'] = $downloadIlosc;
$transmit['transmit'] = 0;
$transmit['created_at'] = $dateNow;
$transmit['updated_at'] = $dateNow;
Auth::user()->transmits()->save($transmit);
//Session::flash('status1', 'Artykuł został dodany poprawnie');
return redirect('warehouse');
But when I trying add only ONE value, for example $transmit['to_user_id'] = $idKey2; then everything works correctly:
$transmit = new transmit($request->all());
$transmit['to_user_id'] = $idKey2;
Auth::user()->transmits()->save($transmit);
return redirect('warehouse');
my file model transmit.php:
protected $fillable = [
'id',
'user_id',
'from_user_id',
'to_user_id',
'product_id',
'quantity',
'transmit',
'created_at',
'updated_at',
];
public function user(){
return $this->belongsTo('App\User');
}
public function products(){
return $this->belongsTo('App\Product');
}
And file add new record (transferProductUser.php):
<div class="col-xs-4">
{!! Form::model(['method'=>'post','class'=>'form-horizontal','action'=>['TransmitsController#updateTransferProduct']]) !!}
Produkt:
<select class="form-control selectpicker show-tick" data-live-search="true" data-size="5" name="products" id="products" onchange="copy()">
<option selected disabled style="color: orange">Wybierz...</option>
#foreach( $listProductOfSelectedUser as $listProduct)
<option data-subtext="(
<?php
$sn = DB::table('products')->select('sn')->where('id', '=', $listProduct->product_id)->get();
$quantity = DB::table($name_user)->select('quantity')->where('product_id', '=', $listProduct->product_id)->get();
?>
#foreach($sn as $serial)
#if($serial->sn == '')
<i>~brak SN~</i>
#elseif($serial->sn)
{{ $serial->sn }}
#endif
#endforeach
#foreach($quantity as $ilosc)
) ilość: <b>{{ $ilosc->quantity }} szt.</b>
#endforeach
" value="{{ $listProduct->product_id }}">
<?php
$article_name = DB::table('products')->select('article_id')->where('id', '=', $listProduct->product_id)->get();
?>
#foreach ($article_name as $name)
{{ article::find($name->article_id)->article_name }}
#endforeach
</option>
#endforeach
</select>
<br />
Do:
<select name="stan2" id="stan2" class="form-control selectpicker show-tick" data-size="5" onchange="run2(event)">
<option selected disabled>Wybierz...</option>
<optgroup id="użytkownicy" value="użytkownicy" label="użytkownicy">
#foreach($userListName as $user)
<option name="użytkownicy" value="{{ $user->id }}">{{ $user->name }}</option>
#endforeach
</optgroup>
<optgroup id="magazyny" value="magazyny" label="magazyny">
#foreach($warehouseList as $warehouse)
<option name="magazyny" value="{{ $warehouse->id }}">{{ $warehouse->name_warehouse }}</option>
#endforeach
</optgroup>
</select>
<div class="checkbox">
<label>
<input type="checkbox" id="isAgeSelected"> Podaj ilość produktów do przeniesienia.
</label>
</div>
<input type="number" class='form-control', id="txtAge" name="count" id="txtAge" style="display:none" min='0', max="", placeholder='Podaj ilość produktow do przeniesienia...'>
<br />
{!! Form::text('stan_key', 'user,'.$userId, ['class' => 'form-control', 'id'=>'copy']) !!}
{!! Form::text('stan_key2', null, ['class' => 'form-control', 'id'=>'copy3']) !!}
{!! Form::text('idProduct', null, ['class' => 'form-control', 'id'=>'copy2']) !!}
{!! Form::submit('Tak, przenieś', ['class' => 'btn btn-primary']) !!}
{!! link_to('warehouse', $title = 'Anuluj', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</div>
<script>
function run2(event) {
console.log(document.getElementById("użytkownicy").label);
var $id = document.getElementById("stan2").value;
var lable=event.target.options[event.target.selectedIndex].parentNode.label
if(lable == 'użytkownicy'){
document.getElementById("copy3").value = "user,"+$id;
} else if (lable == 'magazyny') {
document.getElementById("copy3").value = "warehouse,"+$id;
}
}
document.getElementById('products').onchange = function () {
document.getElementById('copy2').value = event.target.value
}
//wyswietlenie inputa z quantity
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
</script>
Why can't I add all the values at once ??

Seems like when you are trying to
$transmit['to_user_id'] = $idKey2;
Your $idKey contains null or 0.
If you want to have a possibility to set null values, you should make this column nullable.

Related

QueryException error while updating data

Into database not update data, i can't understand my problem, error is below
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update trades set _method = PATCH, _token = AcbGEbEyNxX3e2RzRR2cb1SW6NDvkJuDqFevl0Mr, exchange_id = 1, market_id = 1, symbol_id = 45, is_action = 0, tradedate = , rate = 5000, note = hhhhhhhhh, updated_at = 2018-07-21 13:06:13 where trades.user_id = 33 and trades.user_id is not null and trades.deleted_at is null)
This is my controller
public function edit($id)
{
$trade = Trade::findOrFail($id);
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$symbols = Symbol::pluck('symbol','id')->all();
$reasons = Reason::pluck('reason','id')->all();
return view('member.add-single-trade.edit', compact('trade','reasons', 'exchanges', 'markets', 'symbols'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$tradeID= Auth::user()->trade($id)->update($input);
$reasons=$request->input('reason');
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
$data = array(
'reason_id' =>$reasons,
'trade_id' => $tradeID->id,
);
$test['trade_id']= $tradeID->id;
if($data > 0) {
foreach ($data as $datum) {
$tradeID->tradereason()->update(new TradeReason($datum));
}
}
}
This is my edit.blade.php file
{!! Form::model($trade,['method'=>'PATCH', 'action'=> ['trades\AddSingleTradeController#update',$trade->id]]) !!}
<div class="col-sm-10">
<div class="form-group col-sm-5">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] + $markets, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbols:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options']+ $symbals , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{{ Form::radio('is_action', 1) }} Buy
{{ Form::radio('is_action', 0) }} Sell
</div>
<div class="form-group col-lg-5">
{!! Form::label('tradedate', 'Traded date:') !!}
{!! Form::date('tradedate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-lg-5">
{!! Form::label('rate', 'Traded Rate:') !!}
{!! Form::text('rate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('reason', 'Choose Reasons:') !!}
{{Form::select('reason',$reasons,null, array('id'=>'reasons','multiple'=>'multiple','name'=>'reason[]',"class"=>"js-example-basic-multiple form-control", 'data-width'=>'60%', 'data-live-search'=>'true','onchange' => 'all_function()'))}}
</div>
<div class="form-group col-lg-10">
{!! Form::label('note', 'Note:') !!}
{!! Form::textarea('note', null, ['class'=>'form-control', 'rows' => 2, 'cols' => 40])!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Save', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
<div class="form-group col-lg-4">
{!! Form::open(['method'=>'DELETE', 'action'=> ['trades\AddSingleTradeController#destroy', $trade->id]]) !!}
<div class="form-group">
{!! Form::submit('Delete', ['class'=>'btn btn-danger btn-lg']) !!}
</div>
</div>
{!! Form::close() !!}
This is my create.blade.php file
<td>{{$trade->stoploss}}</td>
You haven't included your model code (probably you are using $guarded = [];) but probably instead of
$input = $request->all();
you should use:
$input = $request->except('_method');
This is because additional _method field is added to form to pass HTTP verb method when using Form::model and obviously you don't have _method field in your table
EDIT
In case you have more fields you can include more fields to ignore for example:
$input = $request->except('_method', '_token');
or you can only use get fields you really want to get for example:
$input = $request->only('exchange_id', 'market_id');
(Of course you should add more fields to above - this is only example)
You can use $fillable property of the model to tell ORM which attributes (columns) can be mass assignable. Any other fields passed via update and create methods will be discarded. check at Laravel docs

Laravel chosen-select retrieving old value from the form

I am trying to retrieve old value from my form on the edit form, but it seems impossible to find an answer, because everyone in the world decided to use Form::select from laravelcollective/html library. I am trying to use the regular HTML to work this, and it's not able to retrieve old value from the form.
This is my HTML Code.
<div class="col-xs-12 form-group">
<label class="control-label">Role*</label>
<select name="roles[]" data-placeholder="Choose a Role for this User..." class="chosen-select" multiple tabindex="4">
<option value="">Select</option>
#foreach ($roles as $key => $value)
<option value="{{ $key }}" {{ in_array($key, old("roles")) ? "selected":"") }} >{{ $value }}</option>
#endforeach
</select>
</div>
This is my controller code.
public function edit($id)
{
$roles = Role::get()->pluck('name', 'id');
$user = User::findOrFail($id);
return view('admin.users.edit', compact('user', 'roles'));
}
I am trying to convert the following into regular html
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('role', trans('global.users.fields.role').'*', ['class' => 'control-label']) !!}
{!! Form::select('role[]', $roles, old('role') ? old('role') : $user->role->pluck('id')->toArray(), ['class' => 'form-control select2', 'multiple' => 'multiple', 'required' => '']) !!}
<p class="help-block"></p>
#if($errors->has('role'))
<p class="help-block">
{{ $errors->first('role') }}
</p>
#endif
</div>
</div>
Try this:
<div class="col-xs-12 form-group {{ $errors->has('role') ? 'has-error' : '' }}">
<label for="role" class="control-label">Role *</label>
<select class="form-control select2" name="role[]" id="role" required multiple>
#foreach ($roles as $id => $label)
<option value="{{ $id }}" #if (collect(old('role', $user->role->pluck('id') ?? []))->contains($id)) selected="selected" #endif>{{ $label }}</option>
#endforeach
</select>
<span class="help-block">
#if ($errors->has('role'))
{{ $errors->first('role') }}
#endif
</span>
</div>
In your controller's update/store function, make sure you either use the built-in validation methods, which will populate the session on any errors.
or
If you have other checks, make sure you return the input when redirecting back.
return redirect()->back()
->withInput() // <- return input with redirect, will populate session
->with('error', 'Persist failed'); // <- optional

Laravel 5.2 How to populate edit form with multiple select?

I want to create a zone which contain few cities. So I decided to use jQuery Select2
Here is my create form multiple selection
<div class="form-group {{ $errors->has('cities') ? 'has-error' : '' }}">
<label>Tentukan Kota</label>
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
#foreach($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endforeach
</select>
</div>
I can multiple select just like in documentation.
Here is my controller which handle display create form
public function zone_create()
{
$cities = City::where('zone_id', null)->get();
return view('backend.admin.pricings.zone_create', compact('cities'));
}
The relationship is One Zone Has Many City.
class Zone extends Model
{
protected $fillable = [
'name',
];
public function cities(){
return $this->hasMany(City::class);
}
}
The city belongs to zone
class City extends Model
{
protected $fillable = [
'zone_id',
'name',
];
public function zone(){
return $this->belongsTo(Zone::class);
}
}
Here is my edit method
public function edit($id)
{
$zone = Zone::find($id);
$cities = City::all();
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities'));
}
Here is my edit form so far
<div class="form-group {{ $errors->has('cities') ? 'has-error' : '' }}">
<label>Tentukan Kota</label>
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
//load option from cities table
//set selected the city belongs to zone
//the other city which don't belong to zone still here for option
</select>
</div>
But how I can populate my edit form (multiple selection) with City belongs to zone?
Just like this in my view
<select name="cities[]" class="city form-control" data-placeholder="Pilih Kota" style="width: 100%;" multiple="multiple">
#foreach($cities as $city)
#if(in_array($city->id, $zoneCityIds))
<option value="{{ $city->id }}" selected="true">{{ $city->name }}</option>
#else
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endif
#endforeach
</select>
and like this in my controller
public function zone_edit($id)
{
$zoneCityIds = [];
$zone = Zone::find($id);
$cities = City::all();
foreach($zone->cities as $zoneCity)
{
$zoneCityIds[] = $zoneCity->id;
}
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities', 'zoneCityIds'));
}
actually it's jus about option tag selected="true"
for multiple values simply use
<div class="form-group">
{!! Form::label('Categories') !!}<br />
{!! Form::select('categories[]', $cost_centers,
$post->categories->pluck('id')->toArray(),
['class' => 'form-control',
'multiple' => 'multiple']) !!}
</div>
In your edit function you can get all the cities of that particular zone
$zone_cities = implode(',',$zone->cities->lists('name')->toArray());
and pass $zone_cities in your view.
return view('backend.admin.pricings.zone_edit', compact('zone', 'cities','zone_cities'));
You will have to use Form Model binding in your view
Read about laravel collective form model binding [here].1
You will open your form like this
Your Edit form will be like this
{!! Form::label('cities','Cities: ') !!}
{!! Form::text('cities',$zone_cities,['class'=>'input','id'=>'cities','aria-required'=>'true','data-seperator'=>',']) !!}

Laravel select optgroup and separated values from database

I write form to send values to database:
{!! Form::model($product, ['method'=>'PATCH','class'=>'form-horizontal','action'=>['ProductsController#updatechangeStatus', $product->id]]) !!}
{{ Form::select('userstan_id', array(
'Użytkownicy' => array($userList),
'Magazyny' => array($warehouseList),
), null, ['class' => 'form-control'])}}
{!! Form::submit('Tak, przenieś', ['class' => 'btn btn-primary']) !!}
{!! link_to('warehouse/'. $product->id, $title = 'Anuluj', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
public function changestatus($id){
$product = Product::find($id);
$userList = User::lists('name', 'id');
$warehouseList = warehouse::lists('name_warehouse', 'id');
return view('pages.changestatus', compact('userList', 'product', 'warehouseList'));
}
Laravel returned values in Form::select like this: http://iv.pl/images/97320689105137896288.png
but I want to return a result like this:
http://iv.pl/images/48707724105931389272.png
How can I do to be returned only name user and name warehouse and value was id number in Laravel (I tring with foreach, but in array foreach not working), like this:
<select>
<optgroup label="Użytkownicy">
<option value="1">michal</option>
<option value="2">mateusz</option>
</optgroup>
<optgroup label="Magazyny">
<option value="1">kosz</option>
<option value="2">zaginione</option>
</optgroup>
</select>
OK I write this: (now Laravel returned records correct look: klik!)
<select name="userstan_id" class="form-control">
<optgroup label="Użytkownicy">
#foreach($userListName as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
#endforeach
</optgroup>
<optgroup label="Magazyny">
#foreach($warehouseList as $warehouse)
<option value="{{ $warehouse->id }}">{{ $warehouse->name_warehouse }}</option>
#endforeach
</optgroup>
</select>
Where name="userstan_id" is name of column where you want save or update record ;)

how to display both id and value in dropdown list in laravel?

This is my code in my View
{{ Form::label('supplier_list', 'Supplier', array('class' => 'control-label')) }}
{{ Form::select('supplier', $supplier_list, null, array('class' => 'form-control')) }}
This is my code in controller
$supplier_list = Supplier::lists('supplier_name', 'id');
My ouput is a Dropdown of SupplierName, what would I need is a Dropdown of displaying both SupplierName and ID, How to do it in laravel 4.2 ?
Try this:
In Controller
$supplier_list = Supplier::lists('supplier_name', 'id')->get();
In Template
<select name="id" class="form-control">
<option value="">Select Supplier Name</option>
#foreach ($supplier_list as $key => $v)
<option value="{!! $v['id'] !!}">{!! $v['supplier_name'] !!}{!! $v['id'] !!}</option>
#endforeach
</select>

Resources