Laravel Eloquent and SUM() - Do not consider the decimal - laravel

I run in a strange issue, I need to sum a column using eloquent but every function I use eloquent do not consider the decimal.
First of all I have the column set ad DECIMAL(8,2) and in my DB the data is stored in the correct way.
If I just use a simple query:
select sum(total_after_tax) from invoice_details where invoice_id = 1
I get the result: 312.93
Now if I use eloquent:
$invoice = Invoice::with(['details'])->get();
dd($invoice->first()->details->sum('total_after_tax'));
I get: 312.
How is this possibile? How can I get the correct value form DB?

Related

Paginate count(*) query issue

Laravel Version: 8.0
PHP Version: 7.3.0
Database Driver & Version: MySQL 5.7.34
Describe the Bug
When I use paginate for pagination the data it call the count( * ) query every time even I pass the column name like count(['id']), and the count( * ) query scan all row in the table.
Table name is users and it has 45 column
Route
Route::get("users", "UsersController#index");
Controller
namespace App\Http\Controllers\Api\V1;
class UsersController extends Controller
{
public function index()
{
return User::paginate(10 , ['id']);
}
}
Call users route
Telescope showing me that two queries
Actual result
Expected result
Steps To Solution:
The following image shows that I had done changes as per our functionality, It will take the first column name from the passed in the paginate method array of $columns params and that query does not scan all columns of the users tables.
Final Results:
I have tired to solving this issue any other way or idea then please let me know
Its not recommended to ever touch the vendor files, you can always just override the functionality inside of your model, you can also pass in the columns to override the getCountForPagination() and you can also pass the columns to simplePaginate() that doesn't invoke any counting!
In order to optimize the query to count and paginate, you can do it like this:
//We will call the query on the model
$program = Program::query()->getQuery();
//count the query by specific columns
$thePaginationCount = $program->getCountForPagination(['id']);
//paginate the results using simplePaginate and select the columns we want:
$thePaginatedProgram = $program->simplePaginate(10, ['id', 'name']);
return 'test: '.$thePaginatedProgram;
Will result like this:
select count(`id`) as aggregate from `programs`
select `id`, `name` from `programs` limit 11 offset 0
As you can see it will only load what we specify and its very efficient!
Final Note:
If you just want to paginate without the count, you can always call Model::simplePaginate($amount, [$columns...])
https://laravel.com/docs/9.x/pagination#simple-pagination

Distinct in Laravel 5 not working properly

I want the distinct names from my database table.The table contains column id and name.
I have tried
$diff=Crud::distinct('name')->get();
$diff=Crud::distinct()->get();
Both of them not worked.They are returning the result with duplicates.Here Crud is my eloquent model.
But when i use
$cnt=Crud::distinct()->count('name'); //returns the correct count
and
$u=Crud::all();
$diff=$u->unique('name'); //returns the distinct names
Why duplicate values are returned while i'm using the distinct? I want distinct names by using distinct.
Thanks.
distinct() doesn't accept arguments. Use one of these options:
$diff = Crud::distinct()->pluck('name');
$diff = Crud::distinct()->get(['name']);
$diff = Crud::distinct()->select('name')->get();

Laravel whereJsonContains in Eloquent giving no results

In the last version of Laravel you have an option to check if Json values are cotaining some values.
Why doesn't this whereJsonContains works like I expected it to work:
$users = User::whereJsonContains('options->foobar', 96)->get();
This is what is stored in the options column (for example):
{"foobar":[96,11,271,256],"sheep":[80,111]}
What I want is to get all Users that have the value 96 in the 'foobar' array.
What is the correct way to do so?
This is the query when I dump it with ->toSql():
select * from "users" where ("options"->'foobar')::jsonb #> ?
So the question is:
How can I show all users that have value 96 in the foobar array of the JSON?
I'm using PostgreSQL.

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;

How to combine and & or operators in grocery crud

I am using codeigniter and grocerycrud, I want to set a table with grocerycrud in this way:
SELECT * FROM `dashboard`.`medidas_ludlum`
where FK_ludlum='190.26.88.131'
and date>= '2014-03-04 09:40:00'
and date<= '2014-03-05 09:40:00'
and (error_code=1 or audio_status=1);
I tried to do that in this way:
$uno='1';
$crud2 = new grocery_CRUD();
$crud2->set_theme('datatables');
$crud2->where('FK_ludlum',$ludlum_id);
$crud2->where('date>=',$fechainicio);$crud2->where('date<=',$fechafin);
$crud2->where('error_code =',$uno);
$crud2->or_where('audio_status =',$uno);
$crud2->set_table('medidas_ludlum');
$crud2->columns('measurement', 'fecha', 'audio_status', 'high_alarm_status', 'low_alarm_status','over_range_status','monitor_status','error_code');
$crud2->set_language("spanish");
$crud2->unset_add();$crud2->unset_delete();$crud2->unset_edit();$crud2->unset_read();
$data['crud2'] = $crud2->render();
However it's not giving the right results, for example I am getting rows that have a date out of the range, is there a way to get that CRUD set up?
Grocery curd is also using codeigniter's active record so you can write your where() with grouped conditions as below,no need to use or_where() function
$crud2->where('(error_code ='.$uno.' OR audio_status ='.$uno.')',null,FALSE);
or
$crud2->where('(error_code =1 OR audio_status =1)',null,FALSE);
The problem in your query is when you use or_where() function it produces where clause as and error_code=1 or audio_status=1 and using approach that i have provide will give you the where clause as and (error_code=1 or audio_status=1) a grouped condition
API and Functions list

Resources