Laravel generate password and insert user in database by hand - laravel

I have few users with no email and password, and I would like to update users by adding email from freemail column, and setup password from random string.
This is my sample code:
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->email = $users->freemail;
$updateUser->remember_token = str_random(10);
$updateUser->motdepasse = $motdepasse;
$updateUser->password = bcrypt($motdepasse);
$updateUser->isfree = 0;
$updateUser->save();
}
The problem is that when I try to connect with email($users->freemail) and password($motdepasse), which is not encrypted random string, I get error that:
my credential is not valid
what did I miss ?

You can use update() to update rows. So your code must be
public function updateUserProfil()
{
//find list user to be update(juste one to test)
$users = User::where('isfree', '1')->first();
//Random string generate
$motdepasse = str_random(6);
//find user
$updateUser= User::find($users->id);
//setup fields
$updateUser->update([
'email'=>$users->freemail,
'remember_token'=>str_random(10),
'motdepasse'=>$motdepasse,
'password'=>bcrypt($motdepasse),
'isfree'=>0,
]);
}

Related

Laravel model is updating multiple models instead of single

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.
I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

I want to retrieve the id from the query result and reuse it for the next query laravel

I want to use the id from the select query results, then I want to use that id again to find data using wherein. but the error i found,
public function getMaut(){
$merek="samsung";
$tipe="led TV";
$display ="25-32";
$kriteria=Kriteria::all();
$alternatif = Alternatif::where('merek',$merek)->where('tipe',$tipe)->where('display',$display)->get();
$alternatif_id = (array)$alternatif->id;
$nilaialter = Nilaialternatif::whereIn('id_alternatifs',$alternatif_id);
return view('spk.index',compact('kriteria','alternatif','nilaialter','alternatif_id'));
}
Use the pluck method to retrieve all values for a given key.
$alternatif = Alternatif::where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get();
$alternatif_id = $alternatif->pluck('id');
$nilaialter = Nilaialternatif::whereIn('id_alternatifs', $alternatif_id)->get();
Alternatively, you can create a hasMany relation to 'Nilaialternatif' at 'Alternatif' model.
class Alternatif extends Model
{
public function nilaialternatifs()
{
return $this->hasMany(Nilaialternatif::class, 'id_alternatifs');
}
}
Then query the relationship like
$alternatif = Alternatif::with('nilaialternatifs')->where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get();
$nilaialter = $alternatif->nilaialternatifs;
$nilaialter = [];
$alternatif = Alternatif::where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get()->toArray();
if (count($alternatif)) {
$alternatif_ids = collect($alternatif)->pluck('id')->toArray();
$nilaialter = Nilaialternatif::whereIn('id_alternatifs', $alternatif_ids)->get()->toArray();
}
use laravel collection, https://laravel.com/docs/6.x/collections
use pluck method of collection,https://laravel.com/docs/6.x/collections#method-pluck

How to update a row from a different row data using laravel

By clicking verify button I want the status of payment to change from pending to verified, then the pending amount (in payments table) to sum up with the wallet balance amount in users table and the final balance updated in users table using Laravel. This is my controller. Please help
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
return redirect()->route('all.payments');
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return back();
}
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return redirect()->route('all.payments');
}

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

Remove First Name, Last Name and confirm password fields in account create page

I searched a lot to remove required fields like first name, Last name and confirm passwordfields in account create page.
So far i renamed required value from 1 to 0 from the table eav_attribute
After this i hided first name, Last Name, Confirm Password from register.phtml
But still i'm getting
The first name cannot be empty, The Last name cannot be empty, etc,..
Did any one know how to do this ?
Please give me a idea to solve this..
You have to change two more files:
Change /js/prototype/validation.js and comment out the following lines:
['validate-cpassword', 'Please make sure your passwords match.', function(v) {
var conf = $('confirmation') ? $('confirmation') : $$('.validate-cpassword')[0];
var pass = false;
if ($('password')) {
pass = $('password');
}
var passwordElements = $$('.validate-password');
for (var i = 0; i < passwordElements.size(); i++) {
var passwordElement = passwordElements[i];
if (passwordElement.up('form').id == conf.up('form').id) {
pass = passwordElement;
}
}
if ($$('.validate-admin-password').size()) {
pass = $$('.validate-admin-password')[0];
}
return (pass.value == conf.value);
}],
After that, you also have to change the Magento Customer Core model. There are two types of validation: through the front-end javascript and in the backend Customer model.
Rewrite the model with your own customer module. Then copy the validate() public function. And comment out the following lines:
$confirmation = $this->getConfirmation();
if ($password != $confirmation) {
$errors[] = Mage::helper('customer')->__('Please make sure your passwords match.');
}

Resources