Laravel select optgroup and separated values from database - laravel

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 ;)

Related

Laravel not validate html select box

I have problem with validating html select. I put rules and all other form controls work fine but only select not show validate message.
Model
class Post extends Model
{
protected $table = 'post';
static $rules = [
'title' => 'required',
'slug' => 'required',
'user_id' => 'required|not_in:0',
'meta_title' => 'required',
'meta_description' => 'required',
'post_category_id' => 'required'
];
}
Blade
<div class="form-group">
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" class="form-control">
<option value="0">Select Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>
Controller
public function store(Request $request)
{
request()->validate(Post::$rules);
$post = Post::create($request->all());
Alert::alert('Success', 'Post created successfully.', 'Type');
return redirect()->route('admin.post.index');
}
What i do wrong here?
Even if the option has the value 0 it is still present so, no error will be triggered for "required" rule
Use a disabled option instead
<select name="post_category_id" class="form-control">
<option disabled>Select a Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select>
As far as I see, you have a default value set on your placeholder of the select, so the input will always be valid since its always sent to the backend.
take a look at this line : Select Category
you're setting a default value, remove it and try again:
in your blade do this:
<div class="form-group">
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" class="form-control">
<option>Select Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>

how to insert multi value data to database in laravel?

I want to store multiple data to database because i have 2 select option with same name. i've following some tutorial from google and youtube but i still can't figured out how to do it.
Table structure:
id | nama_mapel | guru_id | kode_mapel | ki_kd_id |
I have view like this, there's 2 select option with same name:
<input type="text" name="nama_mapel[]">
<input type="text" name="kode_mapel[]">
<select type="text" name="guru_id[]">
<option value disable>Pilih Guru</option>
#foreach ($guru as $item)
<option value="{{ $item->id }}">{{ $item->nama_guru }}</option>
#endforeach
</select>
<select name="ki_kd_id[]">
<option value disable>Pilih Kompetensi Dasar</option>
#foreach ($komp_dasar as $kd)
<option value="{{ $kd->id }}">{{ $kd->kompetensi }}</option>
#endforeach
</select>
<select type="text" name="ki_kd_id[]">
<option value disable>Pilih Kompetensi Inti</option>
#foreach ($komp_inti as $ki)
<option value="{{ $ki->id }}">{{ $ki->kompetensi }}</option>
#endforeach
</select>
and this is my controller:
public function store(Request $request)
{
$nama_mapel = $request->nama_mapel;
$guru_id = $request->guru_id;
$kode_mapel = $request->kode_mapel;
$ki_kd_id = $request->ki_kd_id;
foreach ($nama_mapel as $row => $key){
$data= [
'nama_mapel' => $nama_mapel[$row],
'guru_id' => $guru_id[$row],
'kode_mapel' => $kode_mapel[$row],
'ki_kd_id' => $ki_kd_id[$row],
];
DB::table('mapel')->insert($data);
}
return redirect()->back();
}
Any help would be very appreciated, and sorry for my bad english.
I have found out how to do this.
For view it like this, only use array [] in ki_kd_id name. The reason is because the others is same. I have duplication for all fields except ki_kd_id.
<input type="text" name="nama_mapel">
<input type="text" name="kode_mapel">
<select type="text" name="guru_id">
<option value disable>Pilih Guru</option>
#foreach ($guru as $item)
<option value="{{ $item->id }}">{{ $item->nama_guru }}</option>
#endforeach
</select>
<select name="ki_kd_id[]">
<option value disable>Pilih Kompetensi Dasar</option>
#foreach ($komp_dasar as $kd)
<option value="{{ $kd->id }}">{{ $kd->kompetensi }}</option>
#endforeach
</select>
<select type="text" name="ki_kd_id[]">
<option value disable>Pilih Kompetensi Inti</option>
#foreach ($komp_inti as $ki)
<option value="{{ $ki->id }}">{{ $ki->kompetensi }}</option>
#endforeach
</select>
and for the controller, it will be like this:
public function store(Request $request)
{
foreach ($request->ki_kd_id as $value){
if ($value) {
DB::table('mapel')->insert([
'nama_mapel' => $request->nama_mapel,
'guru_id' => $request->guru_id,
'kode_mapel' => $request->kode_mapel,
'ki_kd_id' => $value,
]);
}
}
return redirect()->back();
}
Use foreach to loop the request based on how many ki_kd_id that the request have. and then for the value just use $value as representative of ki_kd_id

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 insert records (foreign key)

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.

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