Laravel Schema Blueprint Macro


Laravel Schema Blueprint Macro


Since Laravel 5.5, you can now create a custom Schema Blueprint that adds a custom functionality using Macro. To use this feature just simply register the blueprint macro inside your AppServiceProvider. In my case, I needed to add an audit fields on every migration file that I create. To avoid duplications, I register an auditable macro that inserts created_by and updated_by field. 

namespace Yajra\Auditable;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\ServiceProvider;

class AuditableServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        Blueprint::macro('auditable', function() {
            $this->unsignedInteger('created_by')->nullable()->index();
            $this->unsignedInteger('updated_by')->nullable()->index();
        });

        Blueprint::macro('dropAuditable', function() {
            $this->dropColumn(['created_by', 'updated_by']);
        });
    }
}

To use the macro, just simply call it as a function inside the table schema blueprint.

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 100);
    $table->auditable();
    $table->timestamps();
});

 


  • Laravel
  • Auditable