How to subtract two columns from each other when using case expression - php

I want to export some results in Excel from the Model method, so I added this,
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->select(DB::raw("case when pay_type_id=190 then t1.ord_total - t2.pay_amount as Paid_Amount_Online"),
...
->get();
return $records;
}
So as you can see I want to check if the payment type id is equals to 190 that means user has paid it with wallet and the remaining balance is paid online.
So in order to get the Paid_Amount_Online value, I need to subtract the whole order total amount from the payment amount:
case when pay_type_id=190 then t1.ord_total - t2.pay_amount as Paid_Amount_Online
But this obviously wrong and returns syntax error.
So I wonder how can I subtract the amount values from eachother when using sql case expression.

Your
case when pay_type_id=190 then t1.ord_total - t2.pay_amount as Paid_Amount_Online
is raw SQL injected into the query. The syntax is like this:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END
That is:
you start the expression with case
there can be one or more conditions
a condition starts with a when, followed by an expression, continuing with a then and ending with the actual value
you may have an else that stands for a fallback logic when all conditions are false
you end the expression with end
In your code you have a case, a condition with a when and a then, but you are missing its end.

check :
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->select(DB::raw("case when pay_type_id=190 then t1.ord_total - t2.pay_amount end as Paid_Amount_Online"),
...
->get();
return $records;
}
before as use end

here is your solution, if you got any error after this, please post error also, in my answer you can remove else or you can give your comment -
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->select(DB::raw('(CASE WHEN t1.pay_type_id=190 Then t1.ord_total - t2.pay_amount ELSE "No Action Found" End) AS Paid_Amount_Online'),
...
->get();
return $records;
}

You just forgot END at the end of your case expression:
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->select(DB::raw("case when pay_type_id=190 then t1.ord_total-t2.pay_amount as Paid_Amount_Online END as something"),
...
->get();
return $records;
}

Related

How to add if..else conditional statements to the db query builder of Laravel

I have a export method in Laravel 5.8 for exporting some results from oders table:
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->leftjoin('members as t3', 't2.pay_creator_id', '=', 't3.mbr_usr_id')
->where('t2.pay_confirm', 1)
->where('t1.ord_status','completed')
->orWhere('t1.ord_status','processing')
->select('t1.ord_id','t1.ord_date','t1.ord_total','t3.mbr_mobile','t3.mbr_name','t3.mbr_family')
->get();
return $records;
}
So it works fine and clean but I do need to add one more column for checking if the order payment type is by wallet or paid directly.
So every payment has a pay_type_id and if it is set to 189, then it should print Paid With Wallet otherwise print Paid Online as the appended column.
But the problem is, I don't know how to check this if..else condition in this method...
So if you know, please let me know.
Thanks.
you could use case to do if else condition
for example like this
public static function getAllData()
{
$records = DB::table('orders as t1')
->leftjoin('payments as t2', 't1.ord_id', '=', 't2.pay_ord_id')
->leftjoin('members as t3', 't2.pay_creator_id', '=', 't3.mbr_usr_id')
->where('t2.pay_confirm', 1)
->where('t1.ord_status', 'completed')
->orWhere('t1.ord_status', 'processing')
->select(DB::raw("case when pay_type_id=189 then 'Paid With Wallet' else 'Paid Online' end as your_column_name"),'t1.ord_id', 't1.ord_date', 't1.ord_total', 't3.mbr_mobile', 't3.mbr_name', 't3.mbr_family')
->get();
return $records;
}
Try
->select(DB::raw('IF(pay_type_id=189,"Paid With Wallet","Paid Online as") as order_payment_type'))

how to select join in laravel with condition

public function clientcmd()
{
$client = Commande::join('clients', 'commande.id_cli', "=", 'clients.id')
->select('clients.*')
->where('commande.id_cli', '')
->get();
return response()->json($client);
}
I want to select all the client where id client = id cli in command table but that not work they return an empty array
We don't know the data in your table. I assume you want to select fields whose id_cli field is not empty string.
$client = Commande::join('clients', 'commande.id_cli', "=", 'clients.id')
->select('clients.*')
->where('commande.id_cli','!=', '')
->get();
Use Query builder:
use Illuminate\Support\Facades\DB;
$clients = DB::table('clients')
->join('commande', 'commande.id_cli', '=', 'clients.id')
->select('clients.*')
->where(//you can put condition here)
->get();
You can use Client Model to get all client records
$clients = Client::select('*')
->join('commande', 'commande.id_cli', '=', 'clients.id')
->where("clients.id",$client_id) // put your condition here
->get();

Difference between two days laravel query

Are there any way to get difference of two days (today & created_at) using laravel query?
I have tried as follows.but that didn't work for me
public function scopeActivatedOrders($query,$currentDate){
return $query->select('*')
->where('orders.activated', '=', '1')
->where('DATEDIFF(order.arrived_date,$currentDate)','>','14')->get();
}
Thank you!
the problem in your code is that you are using standard where that take a column as the first parameter not an expression ...
you can use whereRaw, or just using DB::raw like:
return $query->select('*')
->where('orders.activated', '=', '1')
->whereRaw('DATEDIFF(order.arrived_date,Now())>14')->get();
note: you can mysql now() function instead of $currentDate variable ...
try this 1st select then add in where condition
public function scopeActivatedOrders($query, $currentDate)
{
return $query->select('orders.*', \DB::raw('DATEDIFF(order.arrived_date, NOW()) as diffday'))
->where('orders.activated', '=', '1')
->get()
->where('diffday', '>', '14');
}

laravel 6 search query with multiple conditions

I have a search form with four fields of customer email, vendor name, status, and fromdate, todate,. My search filter is not working properly. I want if someone searches a lead with vendor name and status Active then it shows only leads of that vendor with status active status but here it shows a leads with both Accept or Reject also my date filter is not working so please help me. Please guide me
my controller code is
public function search(Request $request){
$users = DB::table('users')->where('is_admin', Null)->get();
$customer_email = $request->input('customer_email');
$vendor_id = $request->input('vendor_id');
$status = $request->input('lead_status');
$leads = DB::table('leads')
->leftJoin('users', 'leads.vendor_id', '=', 'users.id')
->select('leads.*', 'users.name')
->where('vendor_id', $vendor_id)
->orWhere('customer_email', $customer_email)
->orWhere('lead_status', $status)
->orWhere('leads.created_at', array($request->start_date, $request->end_date))
->orderBy('leads.created_at', 'DESC')->get();
//dd($leads);
return view('admin.view-leads', compact('leads'), compact('users'));
}
please help.
Thanks in advance
query image
That's a pretty simple thing. Just follow the code below.
To get the users where is_admin is null.
$users = DB::table('users')->whereIsNull('is_admin')->get();
To check if you are submitting a value for any filter.
if($request->filled('name_of_filter_input')){ //code goes here }
So your query to filter records will go like.
$query = DB::table('leads')->query();
$query->leftJoin('users', 'leads.vendor_id', '=', 'users.id');
$query->select('leads.*', 'users.name');
if($request->filled('vendor_id')) {
$query->where('vendor_id', $request->input('vendor_id'));
}
if($request->filled('customer_email')) {
$query->where('customer_email', $request->input('customer_email'));
}
if($request->filled('lead_status')) {
$query->orWhere('lead_status', $request->input('lead_status'));
}
if($request->filled('start_date') && $request->filled('end_date')) {
$query->whereBetween(DB::raw('date(leads.created_at)'), [$request->input('start_date'), $request->input('end_date')]);
}
$leads = $query->orderBy('leads.id', 'DESC')->get();
Further you can replace DB::table('table_name') syntax with respective model classes in case query() seems to be undefined function.
Wrap leads.created_at with date() function and ensure your date filter(s) has date in yyyy-mm-dd format if the created_at column is of type timestamp.
you should write your query like as below
$leads = DB::table('leads')
->leftJoin('users', 'leads.vendor_id', '=', 'users.id')
->select('leads.*', 'users.name')
->where('vendor_id', $vendor_id)
->when($customer_email, function($q,$customer_email){
$q->where('customer_email', $customer_email);
})
->when($status, function($q,$status){
$q->where('lead_status', $status);
})
->where(function($q) use($request){
if(isset($request->start_date) && isset($request->end_date)){
$fromDate = date('Y-m-d H:i:s',strtotime($request->start_date));
$toDate= date('Y-m-d H:i:s',strtotime($request->end_date));
$q->where('leads.created_at', '>=', $fromDate)
->where('leads.created_at', '<=', $toDate);
}
})
->orderBy('leads.created_at', 'DESC')->get();
I updated my answer please look into it

How can I used "if" condition in "whereIn" in laravel

Below is my query which one i used and working fine for me.
if($t_requested['category_id'])
{
$t_query_condition['p.category_id'] = $t_requested['category_id'];
}
if($t_requested['brand_id'])
{
$t_query_condition['p.brand_id'] = $t_requested['brand_id'];
}
$browseData = DB::table('products as p')
->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
'p.short_description','p.product_price','p.special_price','p.stock_quantity')
->orderBy('p.created_by', "desc")
->offset(0)
->limit(10)
->where($t_query_condition)
->get();
but Now i have getting multiple id in "category_id" and "brand_id", i want to used whereIn but it used with of condition. if i get category_id or brand_id null then it's skip.
thanks in advance.
Try this query hope you will get result
$browseData = DB::table('products as p')
->select('p.id as product_id','p.name as product_name','cp.title as category_name','bp.name as brand_name','p.product_weight',
'p.short_description','p.product_price','p.special_price','p.stock_quantity')
->leftjoin('categories as cp', 'p.category_id', '=', 'cp.id')
->leftjoin('brands as bp', 'p.brand_id', '=', 'bp.id')
->orderBy('p.created_by', "desc");
if($t_requested['category_id'])
{
$browseData->whereIn('p.category_id',$t_requested['category_id']);
}
if($t_requested['brand_id'])
{
$browseData->whereIn('p.brand_id',$t_requested['brand_id']);
}
$result=browseData->offset(0)->limit(10)->get();
I think it is very simple, you have to pass array of values instead of one value
I have tried to write options for achieve this, you have to follow which is suitable for you
if($t_requested['category_id'])
{
$t_query_condition['p.category_id'] = $t_requested['category_id']; // it should be array OR
$t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
$t_query_condition['p.category_id'] = explode(",",$t_requested['category_id']); // if you get value comma saperated
$t_query_condition['p.category_id'] = [$t_requested['category_id']]; // if you want to convert one value into array
}

Categories