How to add encrypt task before inputdata goes to dastabase? - laravel-5

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)

Related

Updating email/password not working, undefined variable

I am trying to use a code from https://www.youtube.com/watch v=EM0Wdcux6AE&t=13s&ab_channel=SevenStac , which is very helpful. Although I can't make the updating password/email part.
Error: it shows an error $user is an undefined variable.
I have searched already, tried these:
Undefined variable: users
Undefined variable: user
but they're not applicable in my case because I'm using Laravel 9 with Firebase, firestore database.
I also tried doing:
php artisan cache:clear
php artisan route:clear
Disclaimer, most of these codes are copied from the youtube video. The login credentials, reset password in email, and register worked but not the updating part.
web.php:
Route::resource('/home/profile', App\Http\Controllers\Auth\ProfileController::class)->middleware('user','fireauth');
Note: This is the only line that I included because it is the only relevant part. You can ask if you want more.
settings.blade.php:
{!! Form::model($user, ['method'=>'PATCH', 'action'=> ['App\Http\Controllers\Auth\ProfileController#update',$user->uid]]) !!}
{!! Form::open() !!}
<div class="form-group px-3">
{!! Form::label('email', 'Email ',['class'=>'pt-3 col-12 text-left pl-0']) !!}
{!! Form::email('email', null, ['class'=>'col-md-8 form-control'])!!}
</div>
<div class="form-group px-3">
{!! Form::label('new_password', 'New Password:',['class'=>'col-12 text-left pl-0']) !!}
{!! Form::password('new_password', ['class'=>'col-md-8 form-control'])!!}
</div>
<div class="form-group px-3">
{!! Form::label('new_confirm_password', 'Confirm Password:',['class'=>'col-12 text-left pl-0']) !!}
{!! Form::password('new_confirm_password', ['class'=>'col-md-8 form-control'])!!}
</div>
{!! Form::submit('Save', ['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}
ProfileController.php:
public function index()
{
//
$uid = Session::get('uid');
$user = app('firebase.auth')->getUser($uid);
return view('admin.settings',compact('user'));
}
public function update(Request $request, $id)
{
//
$auth = app('firebase.auth');
$user = $auth->getUser($id);
try {
if ($request->new_password == '' && $request->new_confirm_password =='') {
$request->validate([
'displayName' => 'required|min:3|max:12',
'email' =>'required',
]);
$properties =[
'displayName' => $request->displayName,
'email' => $request->email,
];
$updatedUser = $auth->updateUser($id, $properties);
if ($user->email != $request->email) {
$auth->updateUser($id, ['emailVerified'=>false]);
}
Session::flash('message', 'Profile Updated');
return back()->withInput();
} else {
$request->validate([
'new_password' => 'required|max:18|min:8',
'new_confirm_password' => 'same:new_password',
]);
$updatedUser = $auth->changeUserPassword($id, $request->new_password);
Session::flash('message', 'Password Updated');
return back()->withInput();
}
return $input;
} catch (\Exception $e) {
Session::flash('error', $e->getMessage());
return back()->withInput();
}
Note: in "return $input" it shows an error also, that it is an undefined variable. However, it still worked before when I tried. But when I tried to incorporate my UI with these codes, it did not anymore.
General note: you may be confused that I am using ProfileController with my settings blade, it is because I don't want to move any codes first into my SettingsController, I'm still trying to make it work. Also, it worked before, now it did not.

Livewire validate function got stuck on unique validation

I'm trying to validate a field for unique value. The validate function throws proper validation errors When I enter incorrect/duplicate values but the execution got stuck in validate method and not coming below to dd('save called') when I enter correct/unique values.
I have tried protected $rules[], and protected function rules() but result is the same.
Note: when I remove the unique rule from validation then everything works fine.
here is component code.
public function savePaper($rowIndex)
{
$this->validate([
'rows.*.p1' => ['required', Rule::unique('dutysheets', 'p1')->ignore($this->row['id'])],
]);
dd('save called');
$row = $this->rows[$rowIndex] ?? NULL;
if (!is_null($row)) {
optional(DutySheet::find($row['id']))->update($row);
}
$this->editedRowIndex = null;
$this->editedPaper = null;
}
and here is the view code.
#foreach ($rows as $index => $row)
<tr>
<td scope="row">
<input type="number" style="max-width: 60px;"
wire:model.differ="rows.{{ $index }}.p1"
wire:click="editPaper({{ $index }}, 'p1')"
wire:keydown.enter="savePaper({{ $index }})"
/>
#if ($editedPaper === $index . '.p1')
#error('rows.' . $index . '.p1')
<div class="alert alert-danger">
{{ $message }}
</div>
#enderror
#endif
</td>

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

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!

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources