I'm working on a project that uses Laravel 5.5 and one of the models has its ID defined by the user. Below the model, setting $incrementing to false and having it in the $fillable array.
class AIOpportunity extends Model
{
protected $table = 'ai_opportunity';
protected $primaryKey = 'id_opportunity';
public $incrementing = false;
protected $fillable = [
'id_opportunity',
'budget',
'created_by'
];
}
The problem: when trying to execute this query :
$rec = AIOpportunity::where('id_opportunity', 'abc')->first();
It executed the following query in the database:
select * from ai_opportunity where id_opportunity=abc
Which throws an error because of the type. Is there something else I can do so Eloquent understands it's a varchar field?
I found the issue. It was not a Laravel problem, the settings in my question are OK. The problem was in the database I had locally. Although the table existed and it looked all right when I accessed via PhPMyAdmin I could see it there but also there were error messages saying that the table didn't exist.
Yes, pretty weird. I just deleted the local database and restored a backup from production. it works. The problem was in the database itself, not the Laravel App.
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..
After i set the column in migration like this :
$table->enum('paidBy',['BANK TRANSFERT', 'CARD'])->default('BANK TRANSFERT');
And added to my model :
protected $fillable = ['paidBy'];
protected $visible = ['paidBy'];
I wanted to update the column for a model but it's not working :
$ad->paidBy = 'CARD';
$ad->save();
How can i update it ?
The problem is that i had a mutator for the column paidBy that i forgot to delete. Now it's working
A very common reason why it is not updated is that you forget to set the fillable in the model.
Put in the model you want to update: protected $fillable = ['paidBy'];
in the model.
update
Then try to update withd update function: $ad->update(['paidBy' => 'CARD']);
I have 3 tables that are all Eloquent Models. I'm attempting to use a hasManyThrough, or a pivot, or such to get a relationship from origin table to the last table. I have a hasManyThrough setup now, but Im not getting any results. The query from a dd() looks to be correct as far as the query is built-out, but I don't see any data. There are no errors being thrown.
Tables and ids:
users:
id
apps:
id
user_id
app_id
appversions:
id
app_id
user_id
A user can have many apps. An app can have many versions. I would like to get all versions for a particular user from all of their apps they own. The only one difference is the versions table is called 'appversions' and the model is called version.
I am setting the table name as such on the version model.
class Version extends Model
{
use HasFactory;
protected $table = 'appversions';
}
On my User model, I am attempting this hasManyThrough
public function versions()
{
return $this->hasManyThrough(
'App\Models\Version',
'App\Models\App',
'user_id',
'app_id',
'id',
'app_id'
);
}
And then calling it from my controller like so:
$userVersions = $user->version();
I figured it out and seeing it now.
I changed this:
$userVersions = $user->version();
To this:
$userVersions = $user->version;
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.
I am new in Laravel 4 framework, I am working on library management project. I get all the data from my DB but I can't add a new book to my database.
I've created a form to add new books to my database. I get the Input::get('element') value from my store() method but the create Methode doesn't work . here's my code to save a new book :
Livre::create(array('titre' => Input::get('titre'),
'resume'=> Input::get('resume') ));
and here's my Model :
class Livre extends Eloquent {
protected $table = 'livre';
}
You need to create a new Model instance by calling:
$livre = new Livre;
Then add your 'fields':
$livre->titre = Input::get('titre');
$livre->resume = Input::get('resume');
Then save your new book by calling the save() or push() method:
$livre->save();
Or if you'd like to save a model with its relationships, use the push() method:
$livre->push();
Seems that when you say that create method doesn't work you mean that the record in your DB is created, but it has empty values. This happens when you dont't specify the fields enabled for massive assignment.
By default , the Eloquent model has the guarded attribute set to a wildcard blocking of mass assignment. To use the code that you showed us, modify your model :
class Livre extends Eloquent {
protected $table = 'livre';
protected $fillable = array(
'titre',
'resume'
);
}
You can read more here : Mass Assignment