Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format created_at datetime using Carbon and display result in laravel blade

I'm trying to display created_at datetime into like a minute ago using Carbon inside my laravel blade file. I use vue.js to display the data but not working.

Controller:

public function data()
    {
        $projects = Project::get();
        return [
            'created' => $projects->created_at->diffForHumans()
        ];
        return \Response::json($projects);
    }

Blade with vue:

<tr v-for="Project in Projects">
     <td>@{{ Project.id }}</td>
     <td>@{{ Project.thumb }}</td>
     <td>@{{ Project.name }}</td>
     <td>@{{ Project.active }}</td>
     <td>@{{ Project.created_at }}</td>
</tr>

Error:

Undefined property: Illuminate\Database\Eloquent\Collection::$created_at

I tried also:

foreach ($projects as $project) {
     return [
          'created' => $project->created_at->diffForHumans()
     ];
}

and it displays what I was looking for but it only show just one data.

like image 446
claudios Avatar asked Oct 28 '25 10:10

claudios


1 Answers

I prefer not to format the create_at itself, but instead create a copy of it inside your model, and use it anytime you want.

So within your User.php model:

protected $appends = ['created_date'];

Create an attribute mutator:

public function getCreatedDateAttribute()
{
    return $this->created_at->diffForHumans();
}

Sample Output

10 seconds ago
like image 114
Kreativ James Avatar answered Oct 30 '25 10:10

Kreativ James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!