Laravel - How to Use Carbon in Blade Controller and Model File

Sovary January 12, 2023 430
2 minutes read

Today tutorial we will show you how to use Carbon in template Blade Laravel. We provide example of using Carbon Laravel in view file. If you are searching example of using Carbon in Blade file, then we will give sample example solution. You can follow the tutorial of how to use Carbon class in controller or blade file. This is right place for you to read with short explanation and examples. Laravel Carbon is a library contain Data Time class which help you to solve related to Date Time context.

You can apply Carbon in blade template or controller with version Laravel 6 Laravel 7 Laravel 8 and Laravel 9.

Example #1 - Using Carbon in Blade (View) File

We will use directive @inject to import Carbon class in blade file.

Open file resources/views/index.blade.php

@inject('carbon', 'Carbon\Carbon')
  
<!DOCTYPE html>
<html>
<head>
    <title>Using Carbon in Blade Laravel - CamboTutorial.com</title>
</head>
  
<body>
    <p>{{ $carbon::parse('2022-11-30')->format('d-m-Y') }}</p>
</body>
  
</html>

Output:

11-30-2022

Example #2 - Using Carbon in Controller File

Open file app/Http/Controllers/HomeController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;
  
class HomeController extends Controller
{

    public function index(Request $request)
    {
        $now = Carbon::now()->format('m/d/Y');
        print($now);
  
        $user = User::last();
        $createdDate = Carbon::parse($user->created_at)->format('d/M/Y');
        dd($createdDate );
    }
}

Output:

01/12/2023
12/Jan/2023

Example #3 - Using Carbon in Model File

Open file app/Models/User.php

<?php
  
namespace App\Models;
    
....
use Carbon\Carbon;
  
class User extends Authenticatable
{
    ....
    
   
    public function created_at_format(format)
    {
       return Carbon::parse($this->created_at)->format(format);
    } 
}

Then we can call that property in controller file as below

Open app/Http/Controllers/UserController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{

    public function index()
    {
        $user = User::first();
        print($user->created_at_format('M/d/Y'));
    }
}

Output:

May/23/2022

Thanks for read this article, hope it would help your project. Have a nice day!

You might also like...

Laravel  PHP  Carbon Laravel 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him