1

I have query

SELECT * FROM visitors WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 WEEK);

It worked perfect.I'm trying to convert it to Laravel query

$visitors = DB::table('visitors')->select(DB::raw('*'))
            ->whereRaw('created_at > DATE_SUB(NOW(), INTERVAL 1 WEEK')->get();

I kept getting error

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 (SQL: select * from visitors where created_at > DATE_SUB(NOW() = INTERVAL 1 WEEK)

enter image description here

Can someone help ?

code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

2

There is missing ")" in SQL Query so it is not related to Laravel.

$visitors = DB::table('visitors')->select(DB::raw('*'))
        ->whereRaw('created_at > DATE_SUB(NOW(), INTERVAL 1 WEEK)')->get();

But why are you using raw SQL instead of Carbon?

$visitors = DB::table('visitors')->select(DB::raw('*'))
        ->where('created_at', '>', now()->subWeek())->get();

Also it would be good idea to make model Visitor (https://laravel.com/docs/7.x/eloquent)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Visitor extends Model
{
   //
}

And then your eloquent query will look like this

$visitors = Visitor::where('created_at', '>', now()->subWeek())->get();
chojnicki
  • 3,148
  • 1
  • 18
  • 32
  • Your apostrophe placement is wrong at the end of `whereRaw` ;) – Techno Apr 13 '20 at 16:10
  • Yeah, no code color syntax while typing answer and there it goes :P – chojnicki Apr 13 '20 at 16:13
  • Yeah I like your updated version of your answer better :) – Techno Apr 13 '20 at 16:14
  • Of course not - laravel eloquent is making SQL query anyway :P But you use frameworks (like Laravel) to make life easier and code shorter and cleaner, so why not in this case? – chojnicki Apr 13 '20 at 16:29
  • I agree with you completely. Using it now. Thank-you. – code-8 Apr 13 '20 at 16:30
  • @chojnicki Is what you suggest is making 2 queries under the hood ? I asked about that in details here : https://stackoverflow.com/questions/61192650/how-to-optimize-query-statement-in-laravel-7 – code-8 Apr 13 '20 at 16:52