Francisunoxx Francisunoxx - 1 month ago 12
PHP Question

What's the cause of Call to undefined method Illuminate\Database\Query\Expression::whereRaw()?

I'm trying to perform a query where I need to count

isApprove
column with a value of 1 in my
approvals_document
. Here how I did it in the SQL query.

SELECT documents.id, documents.isApprove,
(SELECT COUNT(*) FROM approvals_document WHERE approvals_document.isApprove = 1 and approvals_document.document_id = documents.id) as approvedBy
FROM documents;


Output:

id | isApprove | approvedBy
96 0 3


When I'm performing this in Laravel using
DB::raw
and
whereRaw
expression. It throws me a error.


Call to undefined method Illuminate\Database\Query\Expression::whereRaw()


Here how I performed it in Laravel way.

public function count()
{
$count = DB::table('documents')
->select('documents.id', 'documents.isApprove', DB::raw('COUNT(FROM approvals_document) as approvedBy')
->whereRaw('approvals_document.isApprove = 1 and approvals_document.document_id = documents.id'))
->get();
dd($count);
}


Any help how did I get this problem? Any help would appreciated!

Update: I followed aynber tips using left join but I got this error.

SC

Answer

You have your parenthesis mixed up. You need an extra one after your select, not after your whereRaw:

$count = DB::table('documents')
->leftJoin('approvals_document','documents.id','=','approvals_document.document_id')
->select('documents.id', 'documents.isApprove', DB::raw('COUNT(approvals_document.*) as approvedBy')) // Close your DB::raw and your select here
->whereRaw('approvals_document.isApprove = 1 and approvals_document.document_id = documents.id')
->get();
Comments