Eloquent is generating bad update query - laravel

I'm trying to update a record just after I get it from database.
$item = Model::find($id);
$item->field = 'foo';
$item->save();
it do finds the requested record, but the query generated to update the record is not correct:
update `Models` set `field` = ? where `id` is null
I don't know why this is happening!
what is wrong ?
Update:
I just renamed the primary-Key from ID to id in the database table. and then it worked! I didn't know it's case-sensitive
update `bannerads_orders` set `ViewedCount` = ? where `id` = ?

Well, I found the problem. as Laravel documents says:
Note: Eloquent will also assume that each table has a primary key
column named id. You may define a primaryKey property to override this
convention
but in my table it was ID not id. so after I changed it to id, everything works as expected.

Laravel uses prepared statements. There is nothing wrong with this. Additionally you don't actually specify an error.

You should probably use in this case:
$item = Model::findOrfail($id);
$item->field = 'foo';
$item->save();
It seems that $id might be null or user cannot be found and than saving it doesn't make any sense.
If user is not found exception will be thrown and this save won't be executed

Related

Problem trying to insert a value from a query with eloquent

i'm trying to select and insert values into a database with eloquent models. The thing is, i made a query to get a value from another table and insert it in the new one. But it keeps inserting 0 when it should insert the value of the id that i'm retrieving
This is the way i'm selecting the id from table clients:
$client_id = Client::select('id')->where('dni', '=', $request->client)->first();
\Log::debug($client_id);
The debug on the Log returns this:
[2020-08-05 17:43:25] local.DEBUG: {"id":1}
And this is the insert:
$seguro = new Seguro();
$seguro->usuario_id = $user_id;
$seguro->cliente_id = $client_id;
$seguro->save();
And the insert is successfull except for the column cliente_id where i'm getting 0 instead of 1.
Can anyone help me with this?
Your $client_id contains object (model), not integer value. You can even see this in debug. Just get id from this model using ->id
$seguro->cliente_id = $client_id->id; // also better change name $client_id to $client
or
$client_id = Client::select('id')->where('dni', '=', $request->client)->first()->id;
Also it is good idea to write code in english (variable names). For example I do not know what "dni" should mean in this query.

not letting a value be nullable with the ->default() on migration

i've been working around and then i tried to make a migration where i establish this:
$table->string('company')->default('None');
$table->string('job')->default('freelancer');
now, that happens is that when i fill out my form, and submit it, it throws me an error message that the fields cannot be NULL.
So i'm a bit confused because as i know, if the fields are NULL, they should be saved as the default part of the migration establishes it.
How can i make it work?
Thanks in advance for your help.
May be you are missing $fillable property in your model:
protected $fillable = ['company','job'];
Also make sure your migrations files are generating correctly. Go to the table and see if default values are set correctly.
Laravel mass assignment
It says if nothing passed to this column when you insert database will set default value as given. But if you try to insert NULL value to this column it will raise error.
If u want to allow NULL value on this column, you should add ->nullable(). Like that:
$table->string('company')->nullable()->default('None');
Let is try to explain more:
Pretend your "column1" is in your fillable array.
When you fill your model without column1. Laravel will generate query like
INSERT INTO table_name(column1) VALUES(NULL)
And if your column1 is not nullable, it will raise error.
if "column1" is not in $fillable array, and you fill your model without "column1", laravel generate query without "column1" like:
INSERT table(othercolumns ... ) VALUEs(....)
Column1 is not set, so MYSQL will set default value there.

Find max value of a column in laravel

The problem started because I have a table (Clientes), in which the primary key is not auto-incremental. I want to select the max value stored in a column database.
Like this select, but with eloquent ORM (Laravel):
SELECT MAX(Id) FROM Clientes
How can I do this?
I tried:
Cliente::with('id')->max(id);
Cliente::select('id')->max(id);
I prefer not to make a simple raw SELECT MAX(ID) FROM Clientes
I cannot make it.
Thanks all!
The correct syntax is:
Cliente::max('id')
https://laravel.com/docs/5.5/queries#aggregates
Laravel makes this very easy, in your case you would use
$maxValue = Cliente::max('id');
But you can also retrieve the newest record from the table, which will be the highest value as well
$newestCliente = Cliente::orderBy('id', 'desc')->first(); // gets the whole row
$maxValue = $newestCliente->id;
or for just the value
$maxValue = Cliente::orderBy('id', 'desc')->value('id'); // gets only the id
Or, if you have a created_at column with the date you could get the value like this
$maxValue = Cliente::latest()->value('id');
Relevant Laravel Documentation: https://laravel.com/docs/5.5/queries#aggregates
$maxValue = DB::table('Clientes')->max('id');
Cliente::where('column_name', $your_Valu)->max('id') // You get any max column
We can use the following code :
$min_id = DB::table('table_name')->max('id');
https://laravel.com/docs/8.x/queries#aggregates

CodeIgniter UPDATE and LIMIT

I know this question has been posted already before Update with limit 1 in codeigniter use active record
But it seems combining UPDATE and LIMIT using Active Record doesnt work on my side. It will still update all record based on the WHERE clause. I'm currently using CodeIgniter 3.0.6. Is this a bug from CodeIgniter already?
screenshot of the query
You cannot directly add limit in update query. I get an alternative way. Firstly you get one row by where query and then run the update query with using fetching row unique key like unique auto increment id.
$singleInfo = $this->db->get_where($tbl, array('user_id'=>1));
$this->db->update($tbl,array('username'=>'FredSmith'),array('user_id'=>$singleInfo->id));
Well I fired up CI 3.0.6 and used this as a demonstration, as we cannot see your setup.
public function db_update_test_with_limit(){
$tbl = 'users';
// Use Chaining - Works
$this->db
->where('user_id',1)
->limit(1)
->update($tbl,array('username'=>'FredSmith'));
echo $this->db->last_query();
// Use discrete calls - Works
$this->db->where('user_id',1);
$this->db->limit(1);
$this->db->update($tbl,array('username'=>'FredSmith'));
echo '<br>';
echo $this->db->last_query();
}
And the results for both are...
UPDATE `users` SET `username` = 'FredSmith' WHERE `user_id` = 1 LIMIT 1
UPDATE `users` SET `username` = 'FredSmith' WHERE `user_id` = 1 LIMIT 1
So if you are doing the same thing and getting different results, then something funky is going on.
If you use this as a test and massage it to suit your situation, does it work or not?

Select one column with where clause Eloquent

Im using Eloquent. But I'm having trouble understanding Eloquent syntax. I have been searching, and trying this cheat sheet: http://cheats.jesse-obrien.ca, but no luck.
How do i perform this SQL query?
SELECT user_id FROM notes WHERE note_id = 1
Thanks!
If you want a single record then use
Note::where('note_id','1')->first(['user_id']);
and for more than one record use
Note::where('note_id','1')->get(['user_id']);
If 'note_id' is the primary key on your model, you can simply use:
Note::find(1)->user_id
Otherwise, you can use any number of syntaxes:
Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first();
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple
Also note, in any of these examples, you can also just assign the entire object to a variable and just grab the user_id attribute when needed later.
$note = Note::find(1);
// $user_id = $note->user_id;

Resources