Hello i have this function which sums the budget_cost and get the data by month
public function marktingCost(){
$costs = \DB::table('campaigns')
->select('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_month'))
->addselect('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_year'))
->groupBy('campaign_leadsource_id')
->where('campaign_status_id',4) // campaign_status_id = 4 means campaign completed
->where(\DB::raw('MONTH(created_at)'), Carbon::today()->month)
->get(); return $costs}
what im trying to achive is get the data by month as budget_total_month and get the data by year as budget_total_year
but i can't use if condition inside query i want to do something like this
->select('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_month') ->where(\DB::raw('MONTH(created_at)'), Carbon::today()->month))
->addselect('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_year') ->where(\DB::raw('Year(created_at)'), Carbon::today()->year))
But of course that's not valid
what i want as output is that
[{"campaign_leadsource_id":1,"budget_total_month":11475,"budget_total_year":134761,"olxTotal":12,"budget_per_lead":11230},{"campaign_leadsource_id":2,"budget_total_month":4221,"budget_total_year":41215,"olxTotal":9,"budget_per_lead":4579}]
thank you in advance
Please try this code.
$costs = \DB::table('campaigns')
->select('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_month'))
->addselect('campaign_leadsource_id', \DB::raw('SUM(budget_cost) as budget_total_year'))
->where('campaign_status_id',4) // campaign_status_id = 4 means campaign completed
->where(\DB::raw('MONTH(created_at)'), Carbon::today()->month)
->groupBy(\DB::raw("MONTH(created_at)"))
->get();
I know you are using laravel classes/methods as an abstraction to SQL. But have you tried using PDO and actual SQL statements to retrieve the data?
Related
This question already has answers here:
Natural ORDER in Laravel Eloquent ORM
(5 answers)
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 6 months ago.
MySQL Database table
Rates:
Id
Name
1
$13.00
2
$20.00
3
$13.75
4
$15.00
5
$100.00
I'm trying to sort the data ASC to show on the dropdown, based on the data you can clearly understand that we can't sort the data by Id.
Here is the same code
$sorted = $rates;
foreach ($rates as $key => $data){
if(preg_match('/[a-z]/', $data['name'])){
unset($sorted[$key]);
$sorted[] = $data;
}
}
Result:
Dropdown
Expected Result:
$13.00
$13.75
$15.00
$100.00
Can you help me to figure this out?
You can try this:
$collection = collect([
['price' => '$13.00'],
['price' => '$12.00'],
['price' => '$15.00'],
]);
$sorted = $collection->sortBy('price');
dd($sorted);
it's very simple instead of sorting data in php, sort data when query table
first of all delete $ in name column and save data as float and change column data type to float
now you can feel sql power
if you want to run sql query manually use this query below
select * from Rates order by Name asc
if you want to use laravel eloquent use this code below
Rate::orderBy('Name','asc')->get();
for more information about order in mysql query see this or in laravel eloquent see this
Guessing ur using eloquent u can sort data when getting it from databse with orderBy
$query = Model::class('params')->orderBy('name', 'asc')->get();
Then when u do #foreach for printing it would be ID for the one with lowest price up until highest, and u dont have to deal with collections.
There is no need to delete your $ sign and change your data structure.
I have a record where I am getting data with timestamps (created_at, updated_at) for last 4 months. Next, I want to divide this data into week wise and month wise (last 4 weeks and last 4 months.)
What I am trying is to manually create variables for each months and then write if logic to enter data into each month. Is there any function that already does it?
// for student population - Last 4 months data
$from = Carbon::now()->subMonth(4);
$to = Carbon::now();
$invoice =invoice::where('instructor_id', '=', $id)
->whereBetween('created_at',[$from,$to])->get();
$week_1=$week_2=$week_3=$week_4=$month_1=$month_2=$month_3=$month_4=[];
// write if logic and enter data for each week separately
No, there is no function that already does it, afaik, in Eloquent or Carbon.
I would suggest looping through the Eloquent Collection.
Here is a hint for you :
$from = Carbon::now()->subMonth(4);
$to = Carbon::now();
$invoices = invoice::where('instructor_id', '=', $id)->whereBetween('created_at', [$from, $to])->get();
// ...
$invoicesLastWeek = $invoices->whereBetween('created_at', [
Carbon::now()->subWeeks(1)->startOfWeek(),
Carbon::now()->subWeeks(1)->endOfWeek()
]);
// ...
$invoicesTwoMonthsAgo = $invoices->whereBetween('created_at', [
Carbon::now()->subMonths(2)->startOfMonth()),
Carbon::now()->subMonths(2)->endOfMonth()
]);
// ...
I would loop and increment parameters for ->subWeeks($i)-> and ->subMonths($i)->, and populate the needed variables.
I would start setting each week vars first, so that I can pop out of the Collection all invoices in that range (for performance). Then for each month vars, I would add weekN + weekN+1 + weekN+2 + weekN+3 vars (and pop them out of the Collection as well, so that I loop faster on a Collection that is getting smaller everytime).
This question already has answers here:
Select Last Row in the Table
(22 answers)
Closed 4 years ago.
public function addNewPost(Request $request)/****ADD new POST****/
{
$this->validate($request,['post_title'=>'required|min:4|max:100',
'post_description'=>'required|min:20|max:500'
]);
$user_name = Session::get('name');
$post_title = $request->input('post_title');
$post_description = $request->input('post_description');
$addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPost->save();
$addPost->post_id;
//$addPost = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->get();
print_r($addAdmin->post_id); //This is printing nothing, i.e. blank.
}
post_id column in userposts table is auto incremented. I am trying to get the last post id of the user by user_name. I have seen some tutorials and also checked some questions over internet but unable to do what I am trying to get. Can anybody know how to do it. Thank you.
Try first() instead of get() in a query it might help you
$lastdata = DB::table('userposts')->where(['user_name'=>$user_name ])->orderBy('post_id', 'desc')->first();
print_r($lastdata);
Laravel has the last() method that you can use.
This is from the docs:
last()
The last method returns the last element in the collection that passes a given truth test:
collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// returns 2
You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:
collect([1, 2, 3, 4])->last();
//returns 4
Here is the example for getting only the last id:
Model::pluck('id')->last();
DB::table('userposts')->last()->pluck('user_name') Is the fastest way .
Make sure to apply last() first to avoid unnecessary workload
Simple method which will not takes much processing is
DB::getPdo()->lastInsertId();
Hope this helps
You can also try
$addPost = new AddNewPost(['user_name'=> $user_name, 'post_title'=> $post_title, 'post_description'=> $post_description]);
$addPost->save();
$addPost->update();
print_r($addPost->post_id); //It will print id..
P.S second method is kind of redundant
Hope this helps
Please have a closer look at your print statement:
print_r($addAdmin->post_id);
The $addAdmin is not defined within the scope of your function. The best way to get the last row from your database:
DB::table('name_of_table')->last()->pluck('user_name')
Here is the documentation on using DB: https://laravel.com/docs/5.6/database
Hello i get stuck on this proble, hope you guys can give me some advice to solve this matter. So, i want to show graph that count basen on month, how many keluhan (complain) on that month. so the table will be like january has 3 complain, febuary has 5 complain, etc (example)
public function lihatkeluhan(){
$halaman="tindaklayanan";
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status'))->get();
$count = count($keluhan_list); //this still not count based on month
$population = Lava::DataTable();
$population->addDateColumn('Year')
->addNumberColumn('Keluhan')
->addRow(['?',$count]);
Lava::LineChart('Population', $population, [
'title' => 'Tahun : 2017',
]);
return view('layanankonsumen.daftarkeluhan',compact('halaman','keluhan_list','lava'));
}
try query like this.
it will gives you groupby result with count of that particular month,
no need for $count = count($keluhan_list); because you will get count in result.
$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,tanggal,produk,username,area,masalah,status,count(*) as count'))
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('m'); // grouping by months
});
I am using laravel framework but in this WhereBetween not working. i am using price range where price starts form 1 to 500. when i set price 1-100
it gives me all the records that is in beetween 1 to 100 i.e. 20,40,50 etc. When i change the value from 1- 150 the above result will not be displayed it gives me no result(20,40,50). Can anyone help me . Here is my Code
enter code here
$products = Product::with("productimages")
->whereBetween('price',[$data['from'], $data['to']])
->get();
Note:- $data['from'] start value i.e 1 and $data['to'] end value i.e 150 or more
I just had the same issue. When the data type of the value is not an integer, it will behave very unpredictably. So the solution is to either change the datatype of the column or cast it while fetching, like this:
$from = $data['from'];
$to = $data['to'];
$products = Product::with("productimages")
->whereRaw("CAST(price AS UNSIGNED) BETWEEN ${from} AND ${to}")
->get();
I actually had this issue on the PostgreSQL jsonb data type, as it always returns nested values as strings, and between fetching doesn't work properly.
Using Where Between
$projects = Product::where('created_at', '>', $data['from'])
->where('created_at', '<', $data['to'])
->get();
OR
$current = Product::with("productimages")
->whereBetween('created_at', array($data['from'], $data['to']))->get();
OR
DB::table('Product')->whereBetween('created_at', array($data['from'], $data['to']))->get();