Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 499
Mustafa Agamey Avatar asked Nov 02 '25 23:11

Mustafa Agamey


2 Answers

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

like image 166
Katerou22 Avatar answered Nov 04 '25 13:11

Katerou22


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

php artisan dump-autoload
like image 31
sathish R Avatar answered Nov 04 '25 13:11

sathish R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!