updateOrCreate cause ErrorException in laravel - php

I wrote a code to login or register users.I used updateOrCreate function to add user if not exist an update a column that is name is verifcode if user exist
controller
users Table:
id(auto increment primary key)|phone|verifcode|timeStmp
---------------------------------
$phone=Input::get('phone');
$code=rand(1001,9999);
$user = new user;
$user = array('phone'=>$phone);
user::updateOrCreate($user,['verifcode' => $code]);
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'users';
protected $fillable = array('phone', 'verifcode','timeStmp');
protected $guarded = array('id');
protected $primaryKey = "id";
public $incrementing = false;
const CREATED_AT= false;
const UPDATED_AT = false;
}
with this code i have folowing error:
array_key_exists(): The first argument should be either a string or an integer that point to vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php file.
i just know that error point to secound argument of UpdateOrCreate function.
thanks for help

If you see at the Model class of laravel framework code, you can note, that updated_at is stored only when it is not dirty.
if (! $this->isDirty(static::UPDATED_AT)) {
$this->setUpdatedAt($time);
}
But isDirty method checks for nulls only.
public function isDirty($attributes = null)
{
$dirty = $this->getDirty();
if (is_null($attributes)) {
return count($dirty) > 0;
}
if (! is_array($attributes)) {
$attributes = func_get_args();
}
foreach ($attributes as $attribute) {
if (array_key_exists($attribute, $dirty)) {
return true;
}
}
return false;
}
So just substitute false with NULL.

If you take a look at the Laravel documentation, you're just using the updateOrCreate method wrong. Look at the flight example there.
In your case it should look like this:
$phone = \Input::get('phone')
$code = rand(1001, 9999);
$user = User::updateOrCreate(
['phone' => $phone],
['verifcode' => $code, 'timeStmp' => \Carbon::now()->timestamp]
);

finally i solve it. by adding Created_at and Update_at columns to table and adding this two coulmn to $guarded in model like this protected $guarded = array('id','CREATED_AT','UPDATED_AT'); and then problem fixed
thanks for help

$phone=Input::get('phone');
$code=rand(1001,9999);
user::updateOrCreate(
['phone' => $phone]
['verifcode' => $code]
);
See if it is work for you.

Related

PHP LARAVEL Update with save() doesn't work sometimes

I have a strange problem. I'm trying to update a database entry with the save function, but the changed columns only update sometimes but most times they do not change yet I don't get any errors.
This is the code in my update function:
public function editadvocatedetails(Request $request){
try {
##get original data
$oldclaimantdets = Clthirdparties::where('claimant_code',$request->claimant_code)->first();
// ##get new data
$claimant_dets = Clthirdparties::where('record_type',$oldclaimantdets->record_type)->where('code',$oldclaimantdets->code)->first();
$claimant_dets->name = $request->name;
$claimant_dets->record_type = $request->record_type;
$claimant_dets->claimant_type = $request->claimant_type;
$claimant_dets->e_mail=$request->e_mail;
$claimant_dets->id_no=$request->id_no;
$claimant_dets->pin_number = $request->pin_number;
$claimant_dets->mobile = $request->mobile;
// // dd($claimant_dets);
$claimant_dets->save();
// dd($claimant_dets);
$mm = $claimant_dets->getChanges();
$user = Auth::user()->user_name;
$process = 'Update Claimant Details';
$claimant_code = $request->claimant_code;
$yy = $this->log_data($mm,$claimant_dets,$user,$process,$claimant_code);
Session::flash('success,'.$request->name.' details has been updated');
return redirect()->back();
} catch (\Throwable $th) {
Session::flash('error,'.$request->name.' failed to be updated');
return redirect()->back();
}
}
My Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
}
When I print the values before the save, I get the correct values for both the old and new data.
It looks like the save() doesn't execute. The redirect is executed.
I'm aware of the update() method, but I used this way for updating entries in my database a lot and until now I never had any problems and I don't get where the problem is.
In the meantime I have reverted to update() to run the update query to solve the problem. But I still want to know why it is happening?
Maybe someone has an idea?
Sometimes hmm..., save() method is formally dependent on $fillable attribute array in the model. So, try defining fillable attributes.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
protected $fillable = ['name','record_type','claimant_type','e_mail','id_no','pin_number','mobile',] ; //include all your attributes here.
}

Calling save() on a model will update every row in the database

I've got the following function in a migration file. The migration is to add a new column, and then update the columns of the existing entries:
<?php
private function updatePlans()
{
$plans = PlanProvider::query()->get();
foreach ($plans as $plan) {
$plan->num_adults = 1;
if (stripos($plan->rate_name, 'couple') !== false) {
$plan->num_adults = 2;
}
$plan->save();
}
}
Now, what's happening here is that when I call save(), it's updating EVERY model, instead of the one inside the loop. I have a similar function for another migration, and it works as expected. Why would this update every model rather than just the one?
$plans is a Collection that contains all your "plans".
Your $plan->save(); is outside your if conditions, so obviously it updates every single row, no matter if it has 1 or 2 num_adults
public function store(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:subscribers'
]);
$subscriber = new Subscriber();
$subscriber->email = $request->email;
$subscriber->save();
Toastr::success('You are Successfully Added Our Subscriber List:)','Success');
return redirect()->back();
}
you can try this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlanProvider extends Model
{
protected $table = 'plan_provider';
protected $guarded = [];
public $timestamps = false;
}
private function updatePlans()
{
$plans = PlanProvider::findOrFail(id);
$plans->num_adults = 1;
$plans->save();
return redirect()->back();
}

array_key_exists() exception error , why not working on false?

I got this error .. When executing with this kind of model initialize false on CREATED_AT and UPDATED_AT i got the error of array_key_exists() , but when i initialize with null values mine model working correctly .. Can anybody explain me why i got this kind of behavior ?
I am using Laravel 5.6 version ..
Seeding: CouponTableSeeder
ErrorException : array_key_exists(): The first argument should be either a string or an integer
at /Applications/XAMPP/xamppfiles/htdocs/sites/FakeProject/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php:1028
1024| // Here we will spin through every attribute and see if this is in the array of
1025| // dirty attributes. If it is, we will return true and if we make it through
1026| // all of the attributes for the entire array we will return false at end.
1027| foreach (Arr::wrap($attributes) as $attribute) {
> 1028| if (array_key_exists($attribute, $changes)) {
1029| return true;
1030| }
1031|
}
1032|
Model:
class Coupon extends Model
{
protected $table = 'coupons';
protected $primaryKey = 'coupon_id';
public $incrementing = false;
const CREATED_AT = false;
const UPDATED_AT = false;
protected $fillable = [
'coupon_id','title','amount','price','type','created_at','expired_at'
];
}
use
public $timestamps = false;
when you don't want created_at and updated_at fields

Laravel / Eloquent - Foreign key always NULL

I have to classes of type Model, WptModel and CacheModel.
use Model;
class CacheModel extends Model {
use \October\Rain\Database\Traits\Validation;
public $timestamps = false;
public $rules = [];
public $table = 'cache';
public $belongsTo = [
'WptModel' => [ 'Models\WptModel' ]
];
public $incrementing = FALSE;
}
use Model;
class WptModel extends Model {
use \October\Rain\Database\Traits\Validation;
public $timestamps = false;
public $rules = [];
public $table = 'wpt';
public $hasOne = [
'CacheModel' => [ 'Models\CacheModel' ]
];
public $belongsTo = [
'GpxModel' => [ 'Models\GpxModel' ]
];
public $incrementing = FALSE;
}
For both models I use firstOrNew to build them.
$wptmodel = WptModel::firstOrNew($values);
$cachemodel = CacheModel::firstOrNew($values);
This works like a charm. but when I try to store $cachemodel in $wptmodel and to save $gpxmodel like this:
$wptmodel->CacheModel = $cachemodel;
$gpxmodel->WptModel = $wptmodel;
$gpxmodel->save();
The following error message appears:
"SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'wpt_model_id' cannot be null (SQL: update
cache` set `wpt_model_id` = where cache`.`wpt_model_id`
= 978a1287-3cad-4580-9c95-8ee2ed13b836 and
cache`.`wpt_model_id` is not null)" on line
662 of laravel/framework/src/Illuminate/Database
/Connection.php
Another thing I won't understand is that is process works for the first time (that means I'm able to insert a row into table cache). The error shows up when I execute these statements the second time (update won't work). If I have a look into the corresponding tables than it looks like that every thing is there. All columns have their values. There is definitifly no NULL-value. So I don't understand why Laravel says that _wpt_model_id_ is NULL.
Thanks in advance for your help.
fw.

laravel mutator that creates a unique random number does not run

I have a Question model like this:
class Question extends Model
{
use SoftDeletes;
protected $primaryKey = 'question_id';
protected $dates = ['deleted_at'];
protected $fillable = ['text', 'code', 'cat', 'answer', 'is_private', 'email', 'parent'];
public function setCodeAttribute ($value)
{
\Debugbar::info('hello');
do {
$code = rand(10000, 10000000);
$user_code = User::where('code', $code)->get();
} while (!$user_code->isEmpty());
return $this->attributes['code'] = $code;
}
}
I want to generate a random integer number and store that in code field on creation of a new instance of the model.
For that I wrote a mutator as you can see but it did not even run.
What is problem?
Well mutator itself do not run untill you don't call $question->code = $someValue.
What you need is observer and define saving method in it that will provide setting of the code attribute value in it like this:
public function saving (Operation $operation)
{
\Debugbar::info('hello');
do {
$code = rand(10000, 10000000);
$user_code = User::where('code', $code)->get();
} while (!$user_code->isEmpty());
return $operation->code = $code;
}
and of corse you need to delete the mutator from the model class as well.

Categories