Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

omobo's avatar
Level 1

Merging date column and time column.

I'm displaying a table with some data. I have two separate columns for a date and a time. I would like to merge the two in one single column in the view.

public function index() {
    $table = Table::all()->sortByDesc("date");

    // Tried this from StackOverflow, but didn't work
    $date_merged = date('d/m/Y H:i:s', strtotime("$table->date $table->time"));

    // Also tried this, which also didn't work
    $date_merged = $table -> date . ' ' . $table -> time;

    return view('welcome')->withData($table);
}

It throws the error: Undefined property: Illuminate\Database\Eloquent\Collection::$date

What can I do?

0 likes
1 reply
koerel's avatar

The all() method returns a collection, not a model. So you have to iterate over the collection and and do the merge on the model (or write an accessor on your model)

For example:

$data = Table::all()->sortByDesc('date')->map(function ($model) {
    $model->dateMerged = $model->date . ' ' . $model->time;
    return $model;
});

return view('welcome')->with(compact('data'));

You could do it in the view as well:

$data = Table::all()->sortByDesc('date');

return view('welcome')->with(compact('data'));

Blade: 

@foreach($data as $item)
    <p>{{$item->date}} {{$item->time}}</p>
@endforeach 

As an accessor on the model:

(Model Table)

public function getDateMergedAttribute()
{
    return $this->date . ' ' . $this->time;
}

Now you would have a date_merged attribute on each model instance

Please or to participate in this conversation.