Change voyager model

2019-07-11 11:43发布

问题:

I want to add some mutators on Voyager's User class, but I won't change anything inside vendor folder, and Voyages uses a User model inside the package. Is it possible for me to, somehow, change this?

回答1:

Simple enough. Modify the default Laravel User model to

<?php

namespace App\Models;

use TCG\Voyager\Models\User as VoyagerUser;

class User extends VoyagerUser {
    // add custom mutators and other code in here
}

Then you can update app/config/voyager.php as @aimme said and have it as

'user' => [
    'add_default_role_on_register' => true,
    'default_role'                 => 'user',
    'admin_permission'             => 'browse_admin',
    'namespace'                    => App\User::class,
],

This way you bring in the power of Voyager's User model to your own with no hackery involved.



回答2:

For most cases extending the vendor packages works fine.

Update voyager configuration

See config/voyager.php

change user array like this. i have changed only namespace here,from voyager user tp App\User.

'user' => [
    'add_default_role_on_register' => true,
    'default_role'                 => 'user',
    'admin_permission'             => 'browse_admin',
    'namespace'                    => App\User::class,
],

but to bring additional changes you could try following way.

Loading whole voyager package as a local package.

Warning: After doing this the package would no longer be a vendor package.

To do that

1 - create a packages folder on the root of the project.

2 - clone the tcg/voyager repo into the packages folder or cut paste vendor tcg folder into packages folder that you created. so you will be having your directories like this yourproject/packages/tcg/voyager . if you have required tcg/voyager in composer.json remove it from there.

3 - update composer.json file on the root of your project. add TCG\\Voyager autoload. see below sample, added the line inside psr-4.

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "TCG\\Voyager\\": "packages/tcg/voyager/src/"
        }
    },

4 - run composer update

sometimes you might have to do composer dump-autoload after bringing changes to the packages.