Search code examples
phplaraveldatelaravel-5php-carbon

Fetch date and convert format using laravel 5.2 eloquent query & carbon


I have controller code which fetches some rows from table and passes those to views, below is the sample result fetched by code

enter image description here

In above image you can check there is show_date and format is Y-m-d , Now I am displaying this date in view as it is currently , but i want to convert this date format to something like this

 21 Sep 2016 ,Wed

My controller code is

 public function show($id)
{
    $cities=General_cities::pluck('city_name','city_id');
    $showtime=Movies_showtimes::with('showdata','movie','cinema')->where([['cinema_id','=',$id],['show_date','>=',Carbon::today()],])->orderBy('show_date', 'asc')->get();

    $cinemahall=Movies_cinemahall::where('cinema_id',$id)->get();
    return view('admin.viewshowtime',compact('cities','showtime','cinemahall'));
}

I am little confused how can i update the eloquent object's all show_date in bulk i.e It should be done after getting eloquent object or It should be fired directly in db query or Is is better to covert date in View.

Help is appreciated.


Solution

  • This is the final answer which worked for this question, thanks to @camelCase and @Borna for figuring out the solution to this answer.

    I used Laravel 5.2 accessor for this solution, check here https://laravel.com/docs/5.3/eloquent-mutators#defining-an-accessor

    This is the accessor code that i wrote in Model which converts dateformat fetched in eloquent collection.

     public function getShowdateAttribute($value)
    {
        $carbon = new Carbon($value);
        return $carbon->format('j M Y, D'); 
    }