In the stars In the stars - 1 month ago 45
PHP Question

PHP Laravel 5 : Trait not found

I am having an issue utilizing traits in a laravel enviroment.

I have attempting to access the trait from wtihin a model in laravel and am getting trait not found error. Below is my trait, this is stored in the app\Traits folder and is named testTrait.php

<?php

namespace App\Traits;


trait test{
public function printTest()
{
$test = 'test';
return $test;
}

}


This is the model I am using to try and access it, this is stored in the app\Models folder and otherwise works fine without attempting to use the trait

<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use App\Traits\testTrait;

class Home extends Model
{
use testTrait;


public function someMethod()
{
/*
something here
*/
}
}


I assume it might have something to do with namespacing and the fact that I have to assign the App\Models namespace but even if I change or remove this it doesn't work.

Answer

Your file may be named testTrait.php, but you've called the trait in that file plain old test.

trait test { ... }

Rename it to testTrait in the testTrait.php file.

trait testTrait { ... }