1

I just started to learn Laravel and converting the regular PHP code to Laravel. I need to execute this query in Laravel, but failed.

SELECT sum(qty_del) as delivery from delivery_sap a where YEAR(a.bill_date) + IF(MONTH(a.bill_date)>6, 1, 0) = 2017

This is what I came up with, but it failes.

$data = DB::table('delivery_sap')
          ->select(DB::raw('sum(qty_del) as delivery'))
          ->whereRaw('YEAR(a.bill_date) + IF(MONTH(a.bill_date)>6, 1, 0) = 2017');

Corrected query based on the answer below

$data = DB::table('delivery_sap')
      ->select(DB::raw('sum(qty_del) as delivery'))
      ->whereRaw('YEAR(bill_date) + IF(MONTH(bill_date)>6, 1, 0) = 2017')
      ->first();

changed from get() to first as I wanted it to return as one row

7
  • 1
    what does the log say? Commented Nov 29, 2016 at 14:00
  • 1
    Use get() at the end of your whereRaw() and see what's the result... Commented Nov 29, 2016 at 14:01
  • What error you are getting? Commented Nov 29, 2016 at 14:02
  • I am new to laravel.. how to view the log ? Commented Nov 29, 2016 at 14:03
  • 1
    Your logs are in /storage/logs Commented Nov 29, 2016 at 14:08

1 Answer 1

2

You can dump the generated query by the query builder and compare it to the original query:

use Illuminate\Support\Facades\DB;

$query = DB::table('delivery_sap')
    ->select(DB::raw('sum(qty_del) as delivery'))
    ->whereRaw('YEAR(a.bill_date) + IF(MONTH(a.bill_date)>6, 1, 0) = 2017');

dd($query->toSql());

It returns:

"select sum(qty_del) as delivery from `delivery_sap` where YEAR(a.bill_date) + IF(MONTH(a.bill_date)>6, 1, 0) = 2017"

Which is almost identical to your original query. You need to chain the calls with a final get() to retrieve the results:

$data = DB::table('delivery_sap AS a')
    ->select(DB::raw('sum(qty_del) as delivery'))
    ->whereRaw('YEAR(a.bill_date) + IF(MONTH(a.bill_date)>6, 1, 0) = 2017')
    ->get(); // <= Here
Sign up to request clarification or add additional context in comments.

5 Comments

I got this log --> local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'App\Http\Controllers\DB' not found'
First, you need to import the facade or the alias into the namespace using a use statement. See the updated answer.
GOT IT..Thanks ! .. Point to note -- I changed the a.bill_date to bill_date as well to make it work
Yeah, right. Or you could just do this: DB::table('delivery_sap AS a').
I edited the question above with the right query. I used first() instead of get() to return one row

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.