How to Use Laravel Macro With Example?

Do you want to Laravel-carbon macro in the Laravel application?

By adding laravel macro service provider in Laravel, we can help us to code reusability and a clean structure in the application.

In this article, we will show How to use Laravel Macro with an example in Laravel blade, So you can easily apply it to your Laravel 5, Laravel 6, Laravel 7, Laravel 8, and Laravel 9 application.

laravel-carbon macro
use Laravel Macro with example

Why you should be using Macros in Laravel

Laravel macros allow us to add custom functionality to Laravel core components or classes. In other words, they allow us to extend Laravel classes.

If you have never heard of or used Laravel Macros before, I’ll try to show you what makes Laravel Macros so unique, how to use them, and how they work internally.

Define macros

In the boot method of AppServiceProvider, we will create a Laravel carbon macro and define a date and time macro and simply format the date and time format.

app\Providers\AppServiceProvider.php :

Now, we can use this Date and Time Format Macro anywhere in the Laravel application.

<?php

namespace App\Providers;
use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Carbon::macro('toFormattedDate', function(){
            return $this->format('d/m/Y');
        });

        Carbon::macro('toFormattedTime', function(){
            return $this->format('H:i A');
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}



In the model make sure you have the field in the cast array.

app\Models\Appointment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use PhpParser\Node\Expr\Cast;
use Illuminate\Support\Carbon;

class Appointment extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [ 
        'date' => 'datetime',
        'time' => 'datetime'];

    public function client()
    {
        return $this->belongsTo(Client::class); 
    }

    public function getStatusBadgeAttribute()
    {
        $badge = [
            'SCHEDULED' => 'primary',
            'CLOSED' => 'success',
        ];
        return $badge[$this->status];
    }
}


Related article:- change the button color based on the status using the Model in Laravel.

Call macros in the blade files

We call the macros from an object context, __call(), like $object->macroName()

resources\views\appointment\list.blade.php

<table class="table table-hover">
   <thead>
      <tr>
         <th scope="col">#</th>
         <th scope="col">Client Name</th>
         <th scope="col">Date</th>
         <th scope="col">Time</th>
         <th scope="col">Status</th>
         <th scope="col">Options</th>
      </tr>
   </thead>
   <tbody>
      @foreach ($appointments as $appointment)
      <tr>
         <th scope="row">{{ $loop->iteration }}</th>
         <td>{{ $appointment->client->name }}</td>
         <td>{{ $appointment->date->toFormattedDate() }}</td>
         <td>{{ $appointment->time->toFormattedTime() }}</td>
         <td>
            <span class="badge badge-{{ $appointment->status_badge }}">{{ $appointment->status }}</span>
         </td>
         <td><a href="#"><i class="fa fa-edit mr-2"></i></a>
            <a href="#"><i class="fa fa-trash text-danger"></i></a>
         </td>
      </tr>
      @endforeach
   </tbody>
</table>

resources\views\users\list.blade.php

<table class="table table-hover">
   <thead>
      <tr>
         <th scope="col">#</th>
         <th scope="col">Name</th>
         <th scope="col">Email</th>
         <th scope="col">Registered Date</th>
         <th scope="col">Options</th>
      </tr>
   </thead>
   <tbody>
      @forelse ($users as $user)
      <tr>
         <th scope="row">{{ $loop->iteration }}</th>
         <td>
            <img src="{{ asset('storage')}}/{{ $user->avatar }}">
            {{ $user->name }}
         </td>
         <td>{{ $user->email }}</td>
         <td>{{ $user->created_at->toFormattedDate() }}</td>
         <td><a href="#"></i></a>
            <a href="#"><i class="fa fa-trash text-danger"></i></a>
         </td>
      </tr>
      @empty
      <tr class="text-center">
         <td colspan="5">No result found</td>
      </tr>
      @endforelse
   </tbody>
</table>

I hope that this article helped you learn Laravel Macro With Example in Laravel. You may also want to check out our guide on how to Display serial number in Laravel application.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com