Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MarkTierney's avatar

Using a trait in all controllers

Hi

I wanted to use an Alert trait on all my controllers so I imported it to the main Controller class (app/Http/Controllers/Controller.php). However none of my controllers could find the trait.

Any idea why?

0 likes
5 replies
tykus's avatar

However none of my controllers could find the trait.

How are you using the trait inside your controllers?

MarkTierney's avatar

Inside say the update method:

return redirect(route('customer.index'))->with(Alert::success('Success message here!'));

Is it because I'm calling static methods on the trait?

MarkTierney's avatar

This is what my base Controller class looks like.

<?php

namespace App\Http\Controllers;

use App\Traits\Alert;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use Alert, AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
MarkTierney's avatar

This works using self::success() instead of Alert::success() -

return redirect(route('customer.index'))->with(self::success('Success message here!'));

Must be bad practice to use static methods on a trait from a parent class maybe?

rawilk's avatar
rawilk
Best Answer
Level 47

This isn't how inheritance works. If you want to use it in your other controllers, you need to import it in them. And by the looks of it, your Alert trait would be better suited as some kind of service class.

1 like

Please or to participate in this conversation.