Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save time in database in timeformat in Laravel 5?

Tags:

laravel-5.2

I have been trying for a while for saving time in my database in timeformat like 10:00:00.

What I want is simply pick up time from timepicker and save data(time) in timeformat.

Here is what I have done:

  • I have used timepicker as it gets data in format 10:52 AM.

  • I have used accessor methods to save time as follows:

    public function setRTimeAttribute($value)
    {
        $this->attributes['r_time'] = date('h:i:A', strtotime($value));
    }
    
  • My post controller in case needed as follows:

    public function postSessionReservation(Request $request,$profile_slug)
    {
        $restaurant = Restaurant::where('slug_profile', $profile_slug)->select('name','ar_name','slug_profile','id')->firstOrFail();
    
        $this->validate($request,[
            'no_of_seats'=>'required',
            'r_date'=>'required',
            'r_time'=>'required',
            'restaurant_id'=>'required',
        ]);
        $data = [
            'no_of_seats'=>$request->no_of_seats,
            'r_date'=>$request->r_date,
            'r_time'=>$request->r_time,
            'restaurant_id'=>$request->restaurant_id
        ];
        $minutes = 1;
    
        Session::put('reservation',json_encode($data),$minutes);
    
        return redirect($restaurant->slug_profile.'/complete-reservation');
    }
    

But it saves the time as 12:00:00 each time.

I do not know how 12:00:00 is generated whenever I save the time. I tried a lot but could not figure out.

Hope you guys will help me solve this.

Thanks in advance.

like image 639
Anand Shrestha Avatar asked May 25 '16 05:05

Anand Shrestha


1 Answers

First remove spaces between time "10 : 52 AM" to "10:52 AM" and then change your line to this

$this->attributes['r_time'] = date("h:i", strtotime( $value ));

This will surely help I already test it.

For example you can remove spaces through

$a = '10 : 52 PM';
$x = preg_replace('/\s*:\s*/', ':', $a);
date("H:i", strtotime($x));
like image 89
Ali Avatar answered Oct 18 '22 01:10

Ali