Search code examples
phplaravel-8sql-date-functions

How to change the timestamp format to string and use it for search function


I tried this ,

$date = date('D, M dS Y g:i a', strtotime('2018-03-01 11:54:33'));
echo $date; // will print Thu, Mar 01st 2018 11:54 am

It worked , but I need same in search function ,

 $table->where("main.no", "like", "%$searchfield%")
       ->orWhere("date('D, M dS Y g:i a', strtotime('timestamp'))", "like", "%searchfield%")

Here , if i search fri in searchfield input box , its showing error as ,

Column not found: 1054 Unknown column 'Thu, Jan 01st 1970 5:30 am' in 'where clause' 

I think its trying to convert "fri" to date or something like that.


Solution

  • You can use this query for searching in orWhere condition:

    $table->where(function($query) use ($searchfield) {
        $query->where("main.no", "like", "%$searchfield%")
              ->orWhere(DB::raw("DATE_FORMAT(main.timestamp, '%a, %b %D %Y %h:%i %p')"), "like", "%$searchfield%");
    });