How to display current date in laravel 8?

Viewed 901

I'm a newbie using laravel, so I want to display the current date on my website. Here's the code that I found on google.

<?php

namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(){
        $date = Carbon::now()->format('d-m-Y');
        // // dd($date);
        return view('home', [
            'title'=>'Home'
        ]);
    }
}

I'm confused how to code in the blade.php file?

3 Answers

You can just use the date function:

{{ date('Y-m-d H:i:s') }}

You can also pass the date directly inside of the view like this.

Current Date: {{ \Carbon\Carbon::now()->format('m/d/Y') }}

You are close, pass the date to the view:

<?php

namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(){
        $date = Carbon::now()->format('d-m-Y');
        // // dd($date);
        return view('home', [
            'title'=>'Home',
            'date' => $date,
        ]);
    }
}

home.blade.php

{{ $date }}

but you could just do it directly in the blade file (as per the comment above) instead of passing it from the controller.

It's also possible to make variables available to all views to avoid having to repeat it.

Related