Problem trying to insert a value from a query with eloquent - laravel

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.

Related

Laravel select table fields by using variables

I want to fetch selected fields from my tables in laravel for that I assign my table fields in a variable. But always it gives me some database query error, here I added my code for that. This working fine when I use direct fields instead of them assign into a variable
$selectedfields = "'table1.*', 'table2.*','table3.column'"
$data = DB::table('table1')
->select($selectedfields)->get();
You can use DB:raw:
$selectedfields = 'table1.*, table2.*, table3.column';
$data = DB::table('table1')
->select(DB::raw($selectedfields))->get();
You might need to join table as well.
your query should be like this
$data = DB::table('table1')
->join('table2','table2.id','=','table1.id')
->join('table3','table3.id','=','table1.id')
->select('table1.*','table2.*','table3.*')->get();

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

Eloquent insert or update query

I have a settings table which i am trying to update. My table is empty and i need to insert some data into it.
I am using eloquent to insert
$s = new Settings;
$s->language = request('language');
$s->sitename = request('sitename');
$s->user_id = Auth::id();
$s->save();
return redirect('settings');
I have come across this function
$se = Settings::findOrNew($id); // if exist then update else insert
The findOrNew requires me to know the id before i can save.
How can insert or update without knowing the id(which may not even exist in the first place).
Well in that cause you can use firstOrNew
since you said your basis is you wanted to check if that user_id already exist in table then you use it as condition instead of id
first -> you use firstOrNew
this function do is
check if condition exist it then if it exist it will just return the first existing data
if not just insert a new data and return the new insert data
$s = User::firstOrNew(array('user_id' => Auth::id()));
Then -> after that you can now use that object and do what you wanted to do on it
$s->language = request('language');
$s->sitename = request('sitename');
$s->save();

Join query in laravel with data manipulation send to view

I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit

Eloquent is generating bad update query

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

Resources