Tools / Laravel Macro's
Macro's are really easy functions you can use to simplify some actions within your Laravel project. Below are two of the macro's I always immediately add to my project;
These go into the boot
function of your App\Providers\AppServiceProvider.php
file
Copied!
// Requires
use Illuminate\Database\Eloquent\Builder;
// Macro
Builder::macro('search', function ($field, $string) {
return $string ? $this->where($field, 'LIKE', '%' . $string . '%') : $this;
});
// Usage
User::search('name', 'Rick De Graaf')->get();
Copied!
// Requires
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
// Macro
Builder::macro('ddSql', function () {
$bindings = $this->getBindings();
$query = $this->toSql();
foreach ($bindings as $binding) {
$query = Str::replaceFirst('?', is_string($binding) ? '"' . $binding . '"' : $binding, $query);
}
dd($query);
});
// Usage
User::where('email', 'noreply@rickdegraaf.com')->ddSql();
// Result
'select * from `users` where `email` = "noreply@rickdegraaf.com" and `users`.`deleted_at` is null'