Home > database >  Pass dynamic value from database to Carbon::now()->subMinutes()
Pass dynamic value from database to Carbon::now()->subMinutes()

Time:02-03

I have a minutes integer column in the db,any way to make the below query work without an additional query? Laravel 8 if it matters.

Contest::latest()->where('created_at','>',  Carbon::now()->subMinutes('minutes')->toDateTimeString())->paginate(4)

;

Reponse ErrorException: A non-numeric value encountered in file

CodePudding user response:

You cannot do this without an additional query. Carbon is a PHP library and won't work within the SQL query. However SQL does provide native functionality for what you need to do:

Contest::latest()
    ->where('created_at','>', DB::raw('NOW()-INTERVAL minutes MINUTE'))->paginate(4)

This should generally work though you may need to replace NOW() with whatever the DBMS provides if not using MySQL.

CodePudding user response:

From seeing documentation, I can see that the method subMinutes() accepts integer as a parameter, not string. Maybe try fixing that one first. When I try Carbon::now()->subMinutes('minutes')->toDateTimeString() running locally, I get a similar error: A non-numeric value encountered.

Information about addition and subtraction of Carbon can be found here

  •  Tags:  
  • Related