How do I create insert related field value from id [Laravel] - laravel

First of all sorry if my title question doesn't make sense, since I don't know how to word my problem and my English not that great. Okay, so
I have my controller
Buy::create([
'master_item_id' => $request->master_item_id,
'quantity_item' => $request->quantity_item,
'price' => $request->price
]);
I have my view
<select id="master_item_id" name="master_item_id"
class="form-control #error('master_item_id') is-invalid #enderror">
<option></option>
#foreach($item as $value)
<option {{ old('master_item_id') ? 'selected' : '' }} value="{{ $value->id }}">
{{ $value->name_item }} |
Rp {{ number_format($value->price, 0, ',', '.')}}
</option>
#endforeach
</select>
How do I create insert 'price' from one form select above? I'm guessing you use where() or maybe find()? I've been flipping through website searching and couldn't find anything. Thanks!

Using the model called MasterItem, this could work:
Buy::create([
'master_item_id' => $request->master_item_id,
'quantity_item' => $request->quantity_item,
'price' => MasterItem::find($request->master_item_id)->price
]);
This does assume that master_item_id in your request represents the id or primary key of the MasterItem model.
If not, and you cannot use find() then this would also work:
Buy::create([
'master_item_id' => $request->master_item_id,
'quantity_item' => $request->quantity_item,
'price' => MasterItem::firstWhere('whatever_the_column_is_called', $request->master_item_id)->price
]);

Related

insert into 2 tables (pivot) array values from multiple select dropdown list

I work with events and years, one event can be in several years and a year can have
several events (pivot table created between the two tables).
I change my single dropdown list in multiple list :
<select id="year_id" type="text" class="form-control selectpicker #error('year_id') is-invalid #enderror" name="year_id[]" required multiple>
<option disabled>--Choisir--</option>
#foreach($years as $year)
#if(old('year') == $year->id)
<option value="{{ $year->id }}" selected>{{ $year->name }}</option>
#else
<option value="{{ $year->id }}">{{ $year->name }}</option>
#endif
#endforeach
</select>
The goal is to select several years for one same event.
I don't know why, but I think I'm not able to validate the form.
This is my controller code :
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'mnemonique' => 'required|string|max:255',
'color' => 'required|string|max:255',
'year_id[]' => 'required|array',
'year_id[].*' => 'required|integer|exists:years,id'
]);
$evenement = new Evenement();
//dd($validatedData);
// $evenement->create($validatedData);
$evenement = Evenement::create($validatedData);
$evenement->years()->sync([$validatedData['year_id[]']]);
I'm not able to insert the events into the pivot table and the new event into the event table.
If I use dd(), I still have a refresh of the form, I think I don't go into the controller...
Do you see something please ?
Thank you in advance.
Change validation rule to
'year_id' => 'required|array',
'year_id.*' => 'required|integer|exists:years,id'
To show Error message in view
#error('year_id')<div class="invalid-feedback">{{$message}}</div> #enderror
and
#if($errors->has('year_id.*')) <div class="invalid-feedback">Selected Year doesnt exists</div> #endif
While saving into database
$evenement->years()->sync($validatedData['year_id']);

Select input with 2 empty option values

In my laravel 5.7/mysql 5 app I have boolean is_quiz field in my vote Table and in model I define:
protected $casts = [
'is_quiz' => 'boolean',
];
...
And array with possible values/keys for using of this fields
private static $voteIsQuizLabelValueArray = Array(1 => 'Is Quiz', 0 => 'Is Not Quiz');
in control I add empty value for empty selector:
$viewParamsArray['voteIsQuizValueArray'] = $this->SetArrayHeader(['' => ' -Select Is Quiz- '], Vote::getVoteIsQuizValueArray(false));
and this array has values:
$viewParamsArray['voteIsQuizValueArray']::Array
(
[] => -Select Is Quiz-
[1] => Is Quiz
[0] => Is Not Quiz
)
In my form this array as :
{{ Form::select('is_quiz', $voteIsQuizValueArray, isset($vote->is_quiz) ? $vote->is_quiz : '', [ "id"=>"is_quiz", "class"=>"form-control editable_field select_input " ] ) }}
and in rendered html-source I see 2 options selected :
<select id="is_quiz" class="form-control editable_field select_input valid" name="is_quiz" aria-invalid="false" aria-describedby="is_quiz-error"><option value="" selected="selected"> -Select Is Quiz- </option><option value="1">Is Quiz</option><option value="0" selected="">Is Not Quiz</option></select>
and validator.w3.org raised error here.
I see what is the reson of the syntax error, but I do not know is there is easy way to fix it ?
Thanks!
Form builder is deprecated since Laravel 5
Why are Form and HTML helpers deprecated in Laravel 5.x?
As one of options you can try use Laravel Collective
https://packagist.org/packages/laravelcollective/html
But IMO the best decision is to build select via blade:
<select id="is_quiz"
class="form-control editable_field select_input valid"
name="is_quiz"
aria-invalid="false"
aria-describedby="is_quiz-error"
>
#foreach ($voteIsQuizValueArray as $k => $v)
<option
value="{{ $k }}"
#if( $k === old('is_quiz', '') ) selected="selected" #endif
>{{ $v }}</option>
#endforeach
</select>

Repopulate old select input

I have a clients table and one of the fields is office. This value can be London or Paris. Within my controller I pass the view the options
public function edit(Client $client)
{
$office = array('London' => 'London', 'Paris' => 'Paris');
return view('clients.edit', compact('client', 'office'));
}
Now within my view I am doing
#foreach($office as $off)
<option value="{{ $client->office }}">{{ $client->office }}</option>
#endforeach
Now $client->office is the previously selected value. So say Paris is saved in the database for the client, the selected option should be Paris and the unselected option should be London.
How can I achieve this?
Thanks
If your array is $office = array('London' => 'London', 'Paris' => 'Paris');
You can try
#foreach($office as $key => $value)
<option value="{{ $value }}" #if($value == $client->office) selected #endif>{{ $key }}</option>
#endforeach

Laravel blade form select statement has index for value

Having searched and tried to resolve this I can't seem to work it out.
I have a simple static method in a class that returns a list of options. I am using this to populate a select element in a form. This works fine but I'm using the Laravel blade shortcut language and the value of each option is coming out as the index of the array, which is sent to the database when persisting the results of the form:
{!! Form::select('type', \App\Http\Utilities\Airporttype::all(), null, ['class' => 'form-control'] ) !!}
HTML produced:
<select class="form-control" id="type" name="type">
<option value="0">Commercial</option>
<option value="1" selected="selected">Military</option>
<option value="2">Galactic</option><option value="3">Private</option>
</select>
Static method called:
class Airporttype
{
protected static $types = [
"Commercial",
"Military",
"Galactic",
"Private",
];
public static function all()
{
return static::$types;
}
}
By using the 'null' option, it will give me the option = selected if the database matches what is already saved for that record.
I can achieve it buy doing the following, but wanted to use the blade shortcode style as it's clean (below is what I have tested elsewhere in te form and works):
<select id="country" name="country" class="form-control">
#foreach (\App\Http\Utilities\Country::all() as $country => $code)
<option value="{{ $country }}" #if ($country == $airport->country) selected = 'selected' #endif>{{ $country }}</option>
#endforeach
</select>
Array dump of Aiporttype::all();
array (size=4)
0 => string 'Commercial' (length=10)
1 => string 'Military' (length=8)
2 => string 'Galactic' (length=8)
3 => string 'Private' (length=7)
Thanks
If I've understood you correctly, you need something like this:
{!! Form::select('type', \App\Http\Utilities\Airporttype::all(), $airport->country, ['class' => 'form-control'] ) !!}
UPDATE:
If you have types in strings, you can try to change your array to:
protected static $types = [
'commercial => 'Commercial',
'military' => 'Military',
'galactic' => 'Galactic',
'private' => 'Private',
];
To get an array indexed by its values you can try something like this
$types = \App\Http\Utilities\Airporttype::all();
$types = array_combine($types, $types);
-- view --
{!! Form::select('type', $types, null, ['class' => 'form-control'] ) !!}
Working Fine for me...
In controller
View::share('types',\App\Http\Utilities\Airporttype::all());
In View
{!! Form::select('types',array(''=>'- Select types -')+$types,Input::get('types',null),array('class'=>'form-control')) !!}
You can use array_flip function in php:
{!! Form::select('type', array_flip(\App\Http\Utilities\Airporttype::all()), $airport->country, ['class' => 'form-control'] ) !!}
Simple elegant function!

Foreach inside a Form::select in Laravel 5.2 + default value

So basicaly I have this select:
<select name="models" id="models" class="form-control">
<option value="0">Select a model</option>
#foreach ($models as $model)
<option value="{$model->id}">{$model->name}</option>
#endforeach
</select>
I fetch my models like this:
$models = Model::all();
And I want to transform this into a {!! Form::select() !!} so this is what I did until now :
{!! Form::select('models', $models)) !!}
and I fetch them like this:
$models= Model::lists('name', 'id');
It is almost perfect, what is missing is the default value. I How can I add that also to the options fetched from my database?
I finally found a solution that works for this case:
$models= Model::lists('name', 'id')->toArray();
{!! Form::select('models', array('' => 'Select a model') + $models) !!}
Pass it as a third argument, Eg,
{{ Form::select('number', [0, 1, 2], 2) }}
Ref: http://laravel-recipes.com/recipes/163/creating-a-select-box-field

Resources