Search code examples
phplaraveleloquentphp-carbon

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


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


Solution

  • 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.