PHP code example of awobaz / eloquent-mutators

1. Go to this page and download the library: Download awobaz/eloquent-mutators library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

awobaz / eloquent-mutators example snippets


Awobaz\Mutator\MutatorServiceProvider::class,

'Mutator'   => Awobaz\Mutator\Facades\Mutator::class,

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Awobaz\Mutator\Mutable;
    
    protected $accessors = [
        'title'   => 'trim_whitespace',
        'content' => 'trim_whitespace',
    ];
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Awobaz\Mutator\Mutable;
    
    protected $accessors = [
        'title'   => ['trim_whitespace', 'capitalize'], 
        'content' => ['trim_whitespace', 'remove_extra_whitespace'],
    ];
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Awobaz\Mutator\Mutable;
    
    protected $mutators = [
        'title'    => 'remove_extra_whitespace',
    ];
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Awobaz\Mutator\Mutable;
    
    protected $accessors = [
        'content' => ['str_replace' => ['one', 'two']]
        //OR 
        //'content' => 'str_replace:one,two'
    ];
}
sh
php artisan mutators:install



namespace App\Providers;

use Awobaz\Mutator\Facades\Mutator;
use Illuminate\Support\ServiceProvider;

class MutatorServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //Register your custom accessors/mutators extensions here.
        Mutator::extend('extension_name', function($model, $value, $key){
            //DO STUFF HERE AND RETURN THE VALUE
        });
    }
}



namespace App\Providers;

use Awobaz\Mutator\Facades\Mutator;
use Illuminate\Support\ServiceProvider;

class MutatorServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //The following extension is an implementation for str_replace
        Mutator::extend('str_replace', function ($model, $value, $key, $search, $replace) {
            return str_replace($search, $replace, $value);
        });
    }
}