PHPackages                             imliam/laravel-macros - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. imliam/laravel-macros

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

imliam/laravel-macros
=====================

A collection of miscellaneous methods to extend some of Laravel's core classes through the use of macros and mixins

v0.1.0(7y ago)36MITPHPPHP ^7.1

Since Jul 14Pushed 7y ago1 watchersCompare

[ Source](https://github.com/ImLiam/laravel-macros)[ Packagist](https://packagist.org/packages/imliam/laravel-macros)[ Docs](https://github.com/imliam/laravel-macros)[ RSS](/packages/imliam-laravel-macros/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

Laravel Macros
==============

[](#laravel-macros)

[![Latest Version on Packagist](https://camo.githubusercontent.com/01f2346b6adcd636befc2a27584748495b0790cec8ecef3aa29481ee435f3701/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696d6c69616d2f6c61726176656c2d6d6163726f732e737667)](https://packagist.org/packages/imliam/laravel-macros)[![Total Downloads](https://camo.githubusercontent.com/fe995acc4bc45003373cbbb5a1fe4cef685c9bf908e949132ce46f783695cb91/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696d6c69616d2f6c61726176656c2d6d6163726f732e737667)](https://packagist.org/packages/imliam/laravel-macros)[![License](https://camo.githubusercontent.com/92e9d1a1841989e71bbfe0a6b21722dc8b19446f890f499126c950054654cf9e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f696d6c69616d2f6c61726176656c2d6d6163726f732e737667)](LICENSE.md)

A collection of miscellaneous methods to extend some of Laravel's core classes through the use of [macros and mixins](https://tighten.co/blog/the-magic-of-laravel-macros).

- [Laravel Macros](#laravel-macros)
    - [Installation](#installation)
    - [Usage](#usage)
        - [Illuminate\\Support\\Collection](#illuminate%5Csupport%5Ccollection)
            - [`Collection@sortByDate($key = null)`](#collectionsortbydatekey--null)
            - [`Collection@sortByDateDesc($key = null)`](#collectionsortbydatedesckey--null)
            - [`Collection@keysToValues()`](#collectionkeystovalues)
            - [`Collection@valuesToKeys()`](#collectionvaluestokeys)
        - [Illuminate\\Database\\Query\\Builder](#illuminate%5Cdatabase%5Cquery%5Cbuilder)
            - [`Builder@if($condition, $column, $operator, $value)`](#builderifcondition-column-operator-value)
        - [Illuminate\\Http\\Request](#illuminate%5Chttp%5Crequest)
            - [`Request@replace($key, $value)`](#requestreplacekey-value)
        - [Illuminate\\Support\\Facades\\Route](#illuminate%5Csupport%5Cfacades%5Croute)
            - [`Route@viewDir($path, $viewDirectory = '', $data = [])`](#routeviewdirpath-viewdirectory---data--)
    - [Testing](#testing)
    - [Changelog](#changelog)
    - [Contributing](#contributing)
        - [Security](#security)
    - [Credits](#credits)
    - [License](#license)

Installation
------------

[](#installation)

You can install the package with [Composer](https://getcomposer.org/) using the following command:

```
composer require imliam/laravel-macros:^0.1.0
```

Usage
-----

[](#usage)

Once installed, all macros will automatically be registered and methods will immediately be available for use.

### Illuminate\\Support\\Collection

[](#illuminatesupportcollection)

#### `Collection@sortByDate($key = null)`

[](#collectionsortbydatekey--null)

Sort the values in a collection by a datetime value.

To sort a simple list of dates, call the method without passing any arguments to it.

```
collect(['2018-01-04', '1995-07-15', '2000-01-01'])->sortByDate();
// return collect(['1995-07-15', '2000-01-01', '2018-01-04'])
```

To sort a collection where the date is in a specific key, pass the key name when calling the method.

```
collect([
    ['date' => '2018-01-04', 'name' => 'Banana'],
    ['date' => '1995-07-15', 'name' => 'Apple'],
    ['date' => '2000-01-01', 'name' => 'Orange']
])->sortByDate('date')
  ->all();

// [
//    ['date' => '1995-07-15', 'name' => 'Apple'],
//    ['date' => '2000-01-01', 'name' => 'Orange'],
//    ['date' => '2018-01-04', 'name' => 'Banana']
// ]
```

Additionally, you can pass a callback to the method to choose more precisely what is sorted.

```
$users = User::all();

$users->sortByDate(function(User $user) {
    return $user->created_at;
})->toArray();

// [
//    ['id' => 12, 'username' => 'spatie', 'created_at' => '1995-07-15'],
//    ['id' => 15, 'username' => 'taylor', 'created_at' => '2000-01-01'],
//    ['id' => 2, 'username' => 'jeffrey', 'created_at' => '2018-01-04']
// ]
```

#### `Collection@sortByDateDesc($key = null)`

[](#collectionsortbydatedesckey--null)

This method has the same signature as the `sortByDate` method, but will sort the collection in the opposite order.

#### `Collection@keysToValues()`

[](#collectionkeystovalues)

Change the collection so that all values are equal to the corresponding key.

```
collect(['a' => 'b', 'c' => 'd'])->keysToValues();
// ['a' => 'a', 'c' => 'c']
```

#### `Collection@valuesToKeys()`

[](#collectionvaluestokeys)

Change the collection so that all keys are equal to their corresponding value.

```
collect(['a' => 'b', 'c' => 'd'])->valuesToKeys();
// ['b' => 'b', 'd' => 'd']
```

### Illuminate\\Database\\Query\\Builder

[](#illuminatedatabasequerybuilder)

#### `Builder@if($condition, $column, $operator, $value)`

[](#builderifcondition-column-operator-value)

Conditionally add where clause to the query builder. [See Mohamed Said's blog post for more information.](https://themsaid.com/laravel-query-conditions-20160425)

Keep chaining methods onto a query being built without having to break it up. Take code like this:

```
$results = DB::table('orders')
    ->where('branch_id', Auth::user()->branch_id);

if($request->customer_id){
    $results->where('customer_id', $request->customer_id);
}

$results = $results->get();
```

And clean it up into this:

```
$results = DB::table('orders')
    ->where('branch_id', Auth::user()->branch_id)
    ->if($request->customer_id, 'customer_id', '=', $request->customer_id)
    ->get();
```

### Illuminate\\Http\\Request

[](#illuminatehttprequest)

#### `Request@replace($key, $value)`

[](#requestreplacekey-value)

Manipulate the request object by replacing a value, or even adding a new one.

```
class Middleware
{
    public function handle($request, \Closure $next)
    {
        $request->replace('key', 'value');

        return $next($request);
    }
}
```

### Illuminate\\Support\\Facades\\Route

[](#illuminatesupportfacadesroute)

#### `Route@viewDir($path, $viewDirectory = '', $data = [])`

[](#routeviewdirpath-viewdirectory---data--)

Mimics the functionality offered by Route::view() method but extends it by rerouting requested the URI at any number of sub-levels to match a view directory in the code base.

This makes it possible to create views with static content and not need to worry about updating routes to match them or using a CMS-style solution to manage them.

For an example, to see how it works, imagine the following route definition:

```
Route::viewDir('/pages', 'pages');
```

And the following directory structure for the views:

```
views/
├── auth/
├── errors/
├── layouts/
├── pages/
│   ├── about-us.blade.php
│   ├── faq.blade.php
│   ├── privacy-policy.blade.php
│   ├── team/
│   │   ├── developers.blade.php
│   │   ├── index.blade.php
│   │   ├── management.blade.php
│   │   └── marketing.blade.php
│   └── terms-of-service.blade.php
└── partials/

```

The following routes will be generated to match each of the views in the given directory:

```
/pages/about-us
/pages/faq
/pages/privacy-policy
/pages/team
/pages/team/developers
/pages/team/management
/pages/team/marketing
/pages/terms-of-service

```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Liam Hammett](https://github.com/imliam)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

23

—

LowBetter than 26% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

2908d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3e8a14b9f997cf85aacea7d39da9dc33c38cc05fe03360578327ea9bcb25f4d9?d=identicon)[ImLiam](/maintainers/ImLiam)

---

Top Contributors

[![imliam](https://avatars.githubusercontent.com/u/4326337?v=4)](https://github.com/imliam "imliam (1 commits)")

---

Tags

laravelmixinsmacrosimliamlaravel macros

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/imliam-laravel-macros/health.svg)

```
[![Health](https://phpackages.com/badges/imliam-laravel-macros/health.svg)](https://phpackages.com/packages/imliam-laravel-macros)
```

###  Alternatives

[werxe/laravel-collection-macros

Custom Laravel Collection macros.

2626.6k](/packages/werxe-laravel-collection-macros)[appstract/laravel-response-macros

Extra Response Macro's for Laravel

321.5k](/packages/appstract-laravel-response-macros)[f9webltd/laravel-redirect-response-macros

Some useful redirect response macros for your Laravel application

212.5k](/packages/f9webltd-laravel-redirect-response-macros)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
