2

I want to get current time of MySQL in Laravel 5.1

What I have done is

    $time = DB::select( DB::raw('SELECT NOW() AS end_time'));
    return $time[0]['end_time'];

I am getting this-

enter image description here

I want to get a output like it-

2015-10-06 17:02:32

Can anyone please help?

4
  • "Not working" is too general. What result or error message do you get? Commented Oct 6, 2015 at 11:07
  • 2
    You are trying to access an object as an array, you will need to do something like: $time[0]->end_time; Commented Oct 6, 2015 at 11:26
  • 1
    Why are you querying your database for the current time? What’s wrong with time() in PHP? Commented Oct 6, 2015 at 11:46
  • @MartinBean sometimes the machine you are running php on is a different time than the database connection, for ETL queries, time is VERY important. Commented Mar 31, 2020 at 17:05

1 Answer 1

5

From the relevant Laravel documentation:

The select method will always return an array of results. Each result within the array will be a PHP StdClass object, allowing you to access the values of the results.

The error you are getting is because you are trying to access the first (and only) result as an array, when it's a StdClass object. So, just try:

$results = DB::select(DB::raw('SELECT NOW() AS end_time'));
return $results[0]->end_time;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.