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
Related
A Laravel relation is displaying null on eager load. However, it works when the relation is accessed normally.
class Student extends Model
{
use SoftDeletes;
public $incrementing = false;
protected $primaryKey = 'id'; // or null
protected $guarded = [];
public function document()
{
return $this->hasOne('App\Model\Document');
}
public function contact()
{
return $this->hasOne('App\Model\Contact');
}
}
The contract relation returns null when I use the following.
Student::with('contact')->get()
However it works when I do the following. What could be the cause of this?
$student = Student::findOrFail($id);
$contact = $student->contact;
Student::with('contact')->get(); returns a Collection of Student instances, which you can loop and access the contact relationship:
$students = Student::with('contact')->get();
foreach($students AS $student){
dd($student->contact);
// Can be `null` or an instance of `Contact`
}
When you call Student::findOrFail($id);, you're getting a single instance of Student, which you can directly access contact:
$student = Student::with('contact')->findOrFail($id);
dd($student->contact);
// Again, can be `null` or an instance of `Contact`
The with() clause is eager loading, and doesn't do anything until you try to access $student->contact, but due to the nature of hasOne(), it can be null.
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.
I have an small API that i want to save into client mysql database.
For this purpose i'm using guzzle.
my controller:
public function index()
{
$http = new \GuzzleHttp\Client;
$res = $http->request('GET', 'http://localhost:8080/api/address');
$addresses = json_decode($res->getBody(),true);
// dd($addresses);
Address::create($addresses);
}
my model:
class Address extends Model
{
protected $primaryKey = 'Adresse';
protected $fillable = ['Adresse', 'Mandant', 'Kategorie', 'Matchcode', 'Name1'];
public $timestamps = false;
}
my migration:
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->integer('Adresse')->primary();
$table->smallInteger('Mandant');
$table->smallInteger('Kategorie')->nullable();
$table->string('Matchcode', 50);
$table->string('Anrede', 50)->nullable();
$table->string('Name1', 50)->nullable();
});
}
my api content:
[
{"Adresse":"1111","Mandant":"0","Kategorie":"0","Matchcode":"fgh8881","Anrede":"Firma","Name1":"Sample name"},{"Adresse":"2399","Mandant":"0","Kategorie":"0","Matchcode":"fgh8882","Anrede":"Firma","Name1":"Sample name 1"}
]
the problem is i get an error
SQLSTATE[HY000]: General error: 1364 Field 'Adresse' doesn't have a
default value (SQL: insert into addresses () values ())
when i limit the api content to one array i can save it without a problem. But if i have more arrays in my api i get this error.
$fillable property on the model is set.
If your primary key is not auto-incrementing the framework needs to know about it.
class Address extends Model
{
protected $primaryKey = 'Adresse';
protected $fillable = ['Adresse', 'Mandant', 'Kategorie', 'Matchcode', 'Name1'];
public $incrementing = false;
public $timestamps = false;
}
Then to add all of the models:
public function index()
{
$http = new \GuzzleHttp\Client;
$res = $http->request('GET', 'http://localhost:8080/api/address');
$addresses = json_decode($res->getBody(),true);
foreach ($addresses as $address) {
Address::create($address);
}
}
Your API content is essentially 2 records. For mass inserting using eloquent you need to use insert not create
So either
1) have your api return 1 result
2) or change Address::create($addresses); to Address::insert($addresses);
Set Adresse be auto-increment as well with primary key and your issue will be solved or If you do not want to set it to auto-increment then assign it to a default value.
check the table structure of addresses whether it have default value NULL need to change default
I want to select an item from the table board by it's PK which is boardId.
However the Board::find(2) or Board::find(1) returns all items, regardless of given parameter.
I have the following table:
With corresponding Lumen Model:
class Board extends CustomModel
{
protected $fillable = [
'userId', 'boardName', 'private'
];
protected $primaryKey = 'boardId';
protected $table = 'board';
}
Custom Model is:
abstract class CustomModel extends Model
{
use Authenticatable, Authorizable;
const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';
}
Calling it with:
$boardId = 2;
return Board::find($boardId)->get();
Also tried:
$boardId = 2;
return Board::find($boardId)->first();
And the following:
$boardId = 2;
return Board::find($boardId)->toSql();
Returns: select * from 'board'. So there is no where boardId = ? or something, which is the problem. What am I doing wrong ?
I'm running PHP 7.2.0 and Lumen 5.5.2. Queries on other models work fine.
You've said you're calling it with get():
return Board::find($boardId)->get();
But you shouldn't add get() because it will return a collection of all objects. Just do this:
return Board::find($boardId);
Just erase the ->get() method this will works for you
I hope be useful
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.