Laravel blade form select statement has index for value - laravel

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!

Related

How do I create insert related field value from id [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
]);

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>

How to add encrypt task before inputdata goes to dastabase?

I made contact-form which all input data goes to a MySQL database.
And when it's saved, it auto replies an email to the customer and me.
This works fine. The next step would be to encrypt that.
Where do I have to put the encrypt task and how?
I just did
php artisan key:generate
and
{{ $contact->name = \Crypt::encrypt($contact->name) }}
I can see encrypt data.
here is my code input date goes database
Contact::create($request->all());
and I would like to know how to decrypt and show all data.
Contact.php ( I fixed twice now)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use EncryptsAttributes;
protected $fillable = [
'type',
'name',
'email',
'gender',
'body'
];
use EncryptsAttributes;
protected $encrypts = [
'type',
'name',
'email',
'gender',
'body'
];
static $types = [
'1',
'2',
'3',
'4'
];
}
and this is my confirm.blade.php
For checking I would like to see the encryped data
<tr>
<th>name</th>
<td>{{ $contact->name }}
(This isn't encrypt)
<br>
{{ $contact->name = \Crypt::encrypt($contact->name) }}
(I this this before I asked here. I can see name encrypeted)
</td>
</tr>
This is my name section of index.blade.php file
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
{!! Form::label('name', 'YOUR NAME:', ['class' => 'col-sm-2 control-label']) !!}
<div class="col-sm-10">
{!! Form::text('name', null, ['class' => 'form-control']) !!}
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
now I got this error
Illuminate \ Database \ Eloquent \ MassAssignmentException
Add [_token] to fillable property to allow mass assignment on [App\Contact].
foreach ($this->fillableFromArray($attributes) as $key => $value) {
$key = $this->removeTableFromKey($key);
// The developers may choose to place some attributes in the "fillable" array
// which means only those attributes may be set through mass assignment to
// the model, and all others will just get ignored for security reasons.
if ($this->isFillable($key)) {
$this->setAttribute($key, $value);
} elseif ($totallyGuarded) {
throw new MassAssignmentException(sprintf(
'Add [%s] to fillable property to allow mass assignment on [%s].',
$key, get_class($this)
));
}
}
return $this;
}
now i got this error
htmlspecialchars() expects parameter 1 to be string, array given (View: C:\xampp\php\041951257234\resources\views\contacts\confirm.blade.php)

Problems with Laravel Pivot Table

I am working on a medical lab application in laravel where I have the following tables:
1. Test table: This is a table which stores all the information related to medical tests:
2: Checkup: This is a page which contains all the patient information along with the tests he/she takes.
This is the test page:
This is the Checkup page where the tests and their results are selected:
Here can be many tests and user can check any number of them and will write the result of the test in the textfield below the checkbox.
I get this data in the controller like below code and save it to the database:
$this->validate($request,
[
'patient_name' => 'required|max:50',
'patient_age' => 'required',
'gender' => 'required',
'patient_type' => 'required',
'technition_id' => 'required',
'result' => 'required',
'test' => 'required',
'amount' => 'required'
]);
if( ($request->patient_type == 2) && ($request->doctor_id==0) )
{
return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid Doctor.']);
}
$checkup = new Checkup;
$checkup->patient_name = $request->patient_name;
$checkup->patient_age = $request->patient_age;
$checkup->gender = $request->gender;
$checkup->patienttype_id = $request->patient_type;
$checkup->technition_id = $request->technition_id;
if(isset($request->doctor_id))
{
$checkup->doctor_id = $request->doctor_id;
}
$checkup->amount = $request->amount;
// $checkup->result = $request->result;
$checkup->save();
$tests =[];
$tests = $request->test;
$results =[];
$results = $request->result;
//$checkup->tests()->attach($tests->id, ['result' => $result]);
$sync_data = [];
for($i = 0; $i < count($tests); $i++)
$sync_data[$tests[$i]] = ['result' => $results[$i]];
$checkup->tests()->sync($sync_data);
Session::flash('success', 'The record was successfully saved.');
return redirect()->route('checkups.index');
Now the problem is that when I check all the checkboxes and write the result of all the tests then it is fine but when I select some and leave some of them then it gives error and the error comes because the result textbox for the unchecked test is empty.
This is the case when I select one test and leave the others:
When I check on test and write the result of it and then var_dump both test and result arrays i get the below output:
In the above image we can see that the test array contains one item because only one checkbox was checked but the result array contains two items and the first one is NULL which belongs to the unchecked checkbox.
This is the view file of the checkboxes and the textfields:
{{ Form::label('tests', 'Tests Taken') }}
#foreach(App\Test::all() as $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[]" type="text" class="form-control">
</div>
#endforeach
<div class="form-group">
{{ Form::label('amount', 'Amount') }}
{{ Form::text('amount', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{Form::button('<i class="fa fa-save"> Save</i>', ['type' => 'submit', 'class' => 'btn btn-success'])}}
</div>
{!! Form::close() !!}
Please help me on this and show me how to insert the pivot table data properly to the system.
Thanks in advance for any help.
Try this..
In your blade file :
#foreach(App\Test::all() as $index => $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[{{ $index }}]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[{{ $index }}]" type="text" class="form-control">
</div>
#endforeach
Instead of the for loop you can use foreach lopp.
$sync_data = [];
foreach($tests as $index => $value) {
if(!empty($results[$index]) {
$sync_data[$value] = ['result' => $results[$index]]
}
}
$checkup->tests()->sync($sync_data);

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