I've just installed new laravel project. After that, I created new Model but when I use create() function, it just show me that my new rows has been duplicated.
This is my code:
protected $fillable = ['id', 'setting_name', 'expected_type', 'default_val', 'modified_val'];
// protected $guarded = ['created_at', 'updated_at'];
function test() {
$input = ['setting_name' => 'Test',
'expected_type' => '123',
'default_val'=>'123',
'modified_val'=>'123'];
// dd($input);
//both next two lines do not working
Setting::create($input);
return Setting::firstOrNew($input);
}
I checked the error :
"Integrity constraint violation: 1062 Duplicate entry '' for key 'setting_name' (SQL: insert into settings (updated_at, created_at) values (1474452834, 1474452834))"
What i did wrong ?
At the end of the day, I realized that I created __constructor for my model, that why I could not create object normally.
I removed that constructor and it works well. :D
The error says you're trying to insert row with setting_name which is already exists in a table and you have unique constraint for this column.
So, make sure you're inserting this row only once and there is no any other row with the same setting_name value.
Related
I'm used to it but today this problem makes me weak..;;
class Market {
// ..
public function ttl()
{
return $this->ttlRelation()->firstOrCreate(
['market_id' => $this->id],
['tier' => 0, 'direction'=>0]
);
}
}
The Market model has one TTL model. I know that firstOrCreate method finds an item as first given array and if it doesn't exists create a new one as persist, returns it.
Besides, its mass-assignment so I filled up $fillable property on ttl model..
class TradingTacticalLayer extends Model
{
public $timestamps = false;
protected $fillable = ['direction', 'tier'];
}
..and I'm getting SQLSTATE[HY000]: General error: 1364 Field 'direction' doesn't have a default value (SQL: insert into "trading_tactical_layer_test" ("tier", "market_id") values (0, 1)) message. I cannot understand why this method won't filled up insert field list proper way. I expect, if I edit $fillable property as ['direction'], SQL would implode ("direction") as insert field and it doesn't.
In general, from my experience, I just set those fields as nullable or manually set a default value. At this time, I want to know why this weird happens and what am I doing wrong.
Well, probably, optimize:clear solve the problem.
I still don't know what makes this error but if you experience mismatch between $fillable property and inserting field list, optimize:clear is an option anyway..
So I'm trying to create a simple REST API using Laravel.
While testing out the API with creating new items to the database I'm receiving an error:
Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (world.cities, CONSTRAINT cities_ibfk_1 FOREIGN KEY (CountryCode) REFERENCES country (Code)) (SQL: insert into cities (Name, CountryCode, District, Population, updated_at, created_at) values (Valhalla, vlh, Ragnar Alley, 200000000, 2020-02-19 01:07:26, 2020-02-19 01:07:26)) in file C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 669
here's the Controller:
public function createCity(Request $request) {
$city = new City;
$city->Name = $request->Name;
$city->CountryCode = $request->CountryCode;
$city->District = $request->District;
$city->Population = $request->Population;
$city->save();
Model:
class City extends Model
{
protected $table = 'cities';
protected $fillable = ['Name', 'CountryCode', 'District', 'Population'];
}
Help would be appreciated as I can't figure out why I'm getting the error after POST.
Thanks in advance.
You try to add vlh as contry_code value into your model .but this field refrence to another model that have country name and in that table there is not any record with this condition and vlh value is unknown or it.
You can romve relation between these models (if it is possible) or first find the id of country that has that code and then insert it into your model.
I was working on an old database which primarykey is 'Id'. Eloquent set up the primary key to default 'id', so it is little change, but still can be confusing. Of course I didnt notice that, and I wanted to save updated models to database. There was no error, and $model->save() return was good but database didn't update. Furthermore I have other functions that get models from the database, and they work as they should without overriding $primarykey.
So here is my question: Why isn't eloquent returning any warnings or errors ? Of course I found in the documentation that I should override $primarykey in the model, and then everything worked perfectly.
I was using MySql 10.1.16-MariaDB.
Here is Laravel controller
public function update(Request $request, Order $order)
{
$order->fill($request->get('data'));
$order->save();
$order->products;
return $order;
}
Vue.js function
editOrder () {
this.fullscreenLoading = true
axios.put('/web/' + this.url + '/' + this.rowId, {'data': this.row})
.then(({data}) => {
this.row = data;
this.fullscreenLoading = false
});
},
Laravel Model was standard, of course my model is now properly updated, when i got this problem there was no $primarykey, I didnt mention $fillable and relationship to products but in my project they are defined and working.
class Order extends Model
{
use LogsActivity;
protected $table = 'orders';
protected $primaryKey = 'Id';
protected $fillable = []
}
If you execute the query with get(), create() or similar method, it will work as before because Eloquent doesn't use PK in this case. But some methods like find() will not work for you until you setup $primaryKey property in the model.
You didn't get an error because there was no error.
When you ran $order->save(), the query generated would have been something like:
update `orders` set `field1` = ?, `fieldN` = ?, `updated_at` = ? where `id` is null
This is a perfectly valid SQL statement, and when it runs, it would produce no errors. However, it will also not update any records (unless you do have a record where the id is null).
The reason why the update query is using null is because your Order model does not have an id attribute, it has an Id attribute, and PHP array keys are case-sensitive. So, when Laravel attempts to get the value for the id attribute, it returns null, and uses that in the query.
Table Structure:
1 ID int(11) AUTO_INCREMENT
2 filename varchar(11) latin1_swedish_ci
3 status int(2)
4 type int(11)
5 created_at timestamp
6 updated_at timestamp
Route::get('/verify1/{data}',function($data){
$task= FileLocation::where('ID',"=",$data)->first();
$task->status = 1;
$task->save();
});
Problem: I tried to return $data. It displays $data=1. I have ID=1 in the table too. Why it doesn't save? Could you please help. This issue screws up my head. I am new to laravel. Thank you.
in FileLocation model class add protected $fillable = array('status');. Mass Assignment will not allow to update this data untill laravel will not know it is ok, to update it. If all data can be changed than add protected $guarded = array(); This and more info on this sub. can be found here
In shortcut:
Once model is created, some attributes, are protected by laravel. This is in case of sensitive data, like: 'id', 'created_at' etc. By default all attributes are protected. It can be change in two ways: (white or black)list. These are protected $fillable or protected $guarded arrays that contain attributes to care of.
class Setting extends Eloquent {
public $primaryKey = 'key';
public $timestamps = false;
public $fillable = array('*');
}
My table settings consists of 2 columns: key and value.
When I try to execute:
Setting::create(array(
'key' => 'test',
'value'=> 'test1'
));
I get:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' (SQL: insert intosettings() values ()) (Bindings: array ( ))
which is extremely weird. Any ideas? I tried this on 2 tables, it has the same problem. My Laravel version is up to date.
Could you please show you database table definition. Are you sure that 'key' is really set as PRIMARY key in your table? The first thing came to my mind is that you probably have different field set as PRIMARY in your 'settings' table ('id' or something) and you didn't set 'auto_increment' flag for that field.