Stephan-v Stephan-v - 7 months ago 57
PHP Question

How to implement laravel custom carbon timestamp?

I want to have a future timestamp for 'contests' that expire in my table. I can input the time without any problem except when I retrieve the input it doesn't seem to return me a carbon instance but merely a string with the time?

public function store(ContestRequest $request)
$input = Request::all();

// Set the 'owner' attribute to the name of the currently logged in user(obviously requires login)
$input['owner'] = Auth::user()->name;

// Set the enddate according to the weeks that the user selected with the input select
$weeks = Request::input('ends_at');

// Add the weeks to the current time to set the future expiration date
$input['ends_at'] = Carbon::now()->addWeeks($weeks);


return redirect('contests');

This is what I am using to create a new contest, the timeformat is exactly the same in the table as the created_at and updated_at fields. They seem to return a Carbon instance when I try something like:


Why am I not getting a carbon instance returned?

My migration file looks like this:



All you have to do is add it to the $dates property in your model.

class Contest extends Model {
    protected $dates = ['ends_at'];

This tells Laravel to treat your ends_at attribute the same as it handles updated_at and created_at

@Jakobud You don't have to worry about overriding created_at and updated_at. They will be merged with the $dates array:

public function getDates()
    $defaults = array(static::CREATED_AT, static::UPDATED_AT);
    return array_merge($this->dates, $defaults);

static::CREATED_AT resolves to 'created_at' and static::UPDATED_AT to 'updated_at'