Traits
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way that reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
Create Trait In Laravel 7
I assume you have Laravel Installed on your system. If you don’t have it, please follow the Official Documentation for How to install Laravel 7.
Okay, let’s start it from here,
At first, I am sorry to say but there is no artisan command for creating Trait, You can install third-party artisan commands. And there is another way the traditional way, know what i mean?
I mean, create a directory Traits inside AppHttp directory. So all of your Traits will be located here AppHttpTraits. and that will be the namespace for all Traits.
Let’s go to your AppHttp directory and create a new directory Traits. And Create a new file let’s say it CommonHelperTrait.php inside the AppHttpTraits directory.
Open the file with your loved IDE or Editor, Paste this code into the file.
namespace AppHttpTraits;
use IlluminateSupportFacadesStorage;
trait CommonTrait {
//your functions here
public function abc()
{
}
}
Now, you can use it on any controllers. LIke bellow
namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesHash;
use AppHttpTraitsCommonTrait;
class HomeController extends Controller
{
use CommonTrait;
public function test()
{
//call trait function
$this->abc();
}
}
That’s it wasn’t it so simple.
Anyway thanks for reading this all. I hope this helped your.
Glad you read it. Thanks.


Leave a Reply