Saturday, February 19, 2022

[FIXED] whereraw Vs DB::raw in Laravel

Issue

I am confused and really don't know how and where should I choose to use one from both ?

I read docs for both

https://laravel.com/docs/5.4/queries#where-clauses

And

https://laravel.com/docs/5.4/queries#raw-expressions

If I use query something like this its not working

DB::table('table_name')
->where('parent_id', $parent_id)
->whereRaw("date",">",$date)
->get();

But it works

DB::table('table_name')
->where('parent_id', $parent_id)
->where(DB::raw("date",">",$date))
->get();

Solution

DB::raw() lets you write raw statements as a part of the query. Eg:

->where(DB::raw('DATE(date_column)'), '>', '2017-01-01')

But if you need to write a complete "raw where", you should use whereRaw (for your convenience). Eg:

->whereRaw('DATE(date_column) > DATE(another_date_column)')

Also, whereRaw() accepts a complete where clause.

So, in your first example it's not working, because you should do it:

->whereRaw("date > ".$date)

And your second example could be simplified by using just whereRaw() like the above statement in my answer.

Also DB::raw() can be used in ->select(),groupBy() and others.



Answered By - Ivanka Todorova

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.