PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 19, 2022

[FIXED] whereraw Vs DB::raw in Laravel

 February 19, 2022     laravel, laravel-5, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing