Saturday, October 28, 2017

How to reuse function in laravel inside different controller (PHP TRAITS)

Tags




Hi guys, I'm back! :D

There a time where we need to use the same function in different controller. To
achieve this, we can use trait.

What is trait? well it like a class but you don't have to initiate it while using it.
Refer here. PHP Traits

So how should we start? refer super easy steps below.


1) Create you Traits Folder. (You can put it anywhere you want but I will store it inside my app folder).

app/Http/Traits  (This is Laravel Folder Structure)


2) Next, you create a file inside the folder. For example I had already created HashPassword.php



Make sure that you input the namespace so that your controller can detect your trait.

3) Next, Inside your Controller  (For example mine is LoginController)

Just insert the code that I circle and you should be able to use the function inside your trait file. (Change the code according to your needs)



Thanks for the support guys! It is the first time where my blog able to reach 2k+ view in just 1 week.

Support me by follow me on google+ or follow my facebook page for more easy tutorial! :)

This Is The Newest Post

1 comments so far

This comment has been removed by the author.


EmoticonEmoticon