Mustafa Agamey
Mustafa Agamey

Reputation: 513

How to use traits in Laravel models?

Hello i'm laravel beginner

I want to make trait and use it in my model but at run time i got error that the trait is not found

my trait :

namespace App;
use Illuminate\Support\Facades\Schema;

trait GeneralModel
{
    public static function testStaticFunction()
    {
        dd('test');
    }
}

my model :

namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use GeneralModel;
}

my controller

namespace App\Http\Controllers;

use App\Comment;

class SearchController extends Controller
{
    public function find()
    {
        Comment::testStaticFunction();
    }
}

error received

Trait 'App\GeneralModel' not found

Upvotes: 4

Views: 8044

Answers (3)

Katerou22
Katerou22

Reputation: 807

In composer.json add this:

  "autoload"    : {
"classmap": [
  "database/seeds",
  "database/factories"
],
"files"   : [

  "app/GeneralModel.php" // <----------- ADD THIS 
],
"psr-4"   : {
  "App\\": "app/"
}},

Then run composer dump-autoload

Upvotes: 3

emtized
emtized

Reputation: 31

You Have to Use

Composer dump-autoload

In Your command line

hope it's help

Upvotes: 0

sathish R
sathish R

Reputation: 422

Please check the GeneralModel.php in app folder. And execute the below command in your project root path.

php artisan dump-autoload

Upvotes: 1

Related Questions