Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Custom Trait Not Found

I'm new to traits, but thought I'd give it a try. But, it doesn't seem to load.

I've created a trait within a folder under the Laravel app directory: app\Helpers called CheckPermsAgainstObjectTrait.php

Here is the trait code:

<?php
namespace App\Helpers;

trait CheckPermsAgainstObjectTrait {
    function something{}
}

I try to use it in a controller as such:

<?php

namespace App\Http\Controllers;

use this&that;
use App\Helpers\CheckPermsAgainstObjectTrait;

class PolicyController extends Controller{

   use CheckPermsAgainstObjectTrait;
}

Classes in that directory load fine. PHPStorm sees the trait fine. I've clear compiled aritsan and dumped autoload. I'm guessing there is something that Laravel doesn't like with the namespacing? I would hope I don't need to do any manual loading in composer -- but I'm having trouble finding any documentation to give me a hint as to what I'm screwing up.

The error:

FatalErrorException in PolicyController.php line 15: 
Trait 'App\Helpers\CheckPermsAgainstObjectTrait' not found

Any thoughts?

like image 771
Watercayman Avatar asked May 29 '16 15:05

Watercayman


2 Answers

Did you dump autoload files?

composer dump-autoload
like image 70
huuuk Avatar answered Sep 18 '22 05:09

huuuk


The answer for me was that I had the wrong namespace at the top of my trait file due to working from a Laravel trait as an example. If your trait is in App/Traits/MyTrait.php then make sure your namespace is:

namespace App\Traits;

trait MyTrait
{
    // ..
}

Then from the file that's including the trait:

use App\Traits\MyTrait;

class MyClass
{
    use MyTrait;

    // ..
}

No need to mess with config/app.php, composer.json or autoloading.

like image 26
Zack Morris Avatar answered Sep 18 '22 05:09

Zack Morris