0

Here is the original code:

$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" ');
return $invoice[0]->invoice_number;

The above works great, but I want to use it like this:

$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" where depa_series = "2" ');
return $invoice[0]->invoice_number;

But this gives the following error:

Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 
check the manual that corresponds to your MariaDB server version for the right syntax 
to use near ' where depa_series = "2"' at line 1 (SQL: SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "140", where depa_series = "2" )

How to use multiple WHERE clauses in DB::select? Thank you!

3 Answers 3

3

The query gives a syntax error, because you use where twice.

Try to change it to this, by using the AND condition:

DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" AND depa_series = "2"');
Sign up to request clarification or add additional context in comments.

Comments

3

Have a look at the selectRaw method

$invoice = DB::table('invoices')
            ->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number')
            ->where('company_id', company()->id)
            ->where('depa_series', "2")
            ->get();

return $invoice[0]->invoice_number;

Comments

0

here is what you should do $invoice =

DB::table('invoices') ->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number') ->where(['company_id', company()->id, 'depa_series', "2"]) ->get(); return $invoice[0]->invoice_number;

There will no need to using multiple where statements. You can just put all in an array.

Comments

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.