Skip to content
Advertisement

ELOQUENT – Calculating difference of datetimes in where-clause

I am trying to check if the difference of two columns in my database is under a given amount of years – meaning DATETIME – BIRTHDATE < years

I have tried;

However, I get an error telling me that the;

return type of strtotime is a boolean

Now I’m running out of ideas. Any help would be appreciated.

Edit: for clarification: Value.php:

and Student.php

In the students table I saved:

In the values table it is:

2nd edit:

Thanks to @motia, I’ve edited my code:

This reads the age from the request, working perfectly fine.. but then..:

throws an error stating:

SQLSTATE[HY000]: General error: 1 no such function: TIMESTAMPDIFF (SQL: select * from “values” where exists (select * from “students” where “values”.”student_id” = “students”.”id” and TIMESTAMPDIFF(YEAR, students.birth, datetime) < 19))

(19 was my example value for age)

Advertisement

Answer

In your code, you are executing the condition to filter the table in your PHP code rather then building the query and let the database execute the SQL.

When querying you should think of building the correct SQL experession string.

For your case the condition expression you need can not be built with query->where, so you need to use query->whereRaw

EDIT The example abovee works only on mysql databases. For SQLITE, the condition should be

And for PostgreSQL

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement