Skip to content
Advertisement

use multiple Trait in laravel Controller

problem in use multiple Trait in Controller

Traits

trait A
{
    public function name()
    {
        return 'A';
    }
}
trait B
{
    public function name()
    {
        return 'B';
    }
}
trait C
{
    public function name()
    {
        return 'C';
    }
}
trait D
{
    public function name()
    {
        return 'D';
    }
}

in CRController

class CRController extends Controller
{
    use A {
        name AS A_name;
    }
    use B {
        name AS B_name;
    }
    use C {
        name AS C_name;
    }
    use D {
        name AS D_name;
    }
}

error log

[2021-10-11 14:19:40] local.ERROR: Trait method CREATES_IS_NAME_METHOD has not been applied, because there are collisions with other trait methods on AppHttpControllersPanelCRController {"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 64): Trait method CREATES_IS_NAME_METHOD has not been applied, because there are collisions with other trait methods on App\Http\Controllers\PNAME\CRController at /var/www/html/app/Http/Controllers/PNAME/CRController.php:26)
[stacktrace]
#0 {main}
"} 
$ php -v
PHP 7.2.24 (cli) (built: Oct 22 2019 08:28:36) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

exec command…

composer dump-autoload

composer dump-autoload -o

php artisan config:clear

php artisan view:clear

php artisan route:clear

php artisan cache:clear

not wotking!

Advertisement

Answer

This is called Conflict Resolution. In a simple terms, you need to select a default name method so to speak.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to choose exactly one of the conflicting methods.

All you need to need is to use A::name instead of the others. and define another names for the other trait methods.

class CRController extends Controller
{
    use A {
        A::name insteadof B,C,D;
        A::name AS A_name;
    }
    use B {
        B::name AS B_name;
    }
    use C {
        C::name AS C_name;
    }
    use D {
        D::name AS D_name;
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement